12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <?PHP
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Headers: *');
- header('Access-Control-Allow-Methods: *');
- header('Content-Type: application/json; charset=UTF-8');
-
- //Database Connection
- $host = 'localhost';
- $dbname = 'censo';
- $user = 'luis.ortiz79';
- $passw = '27gnpXrDmPUPzEPQ';
-
- try{
- $connection = mysqli_connect($host, $user, $passw, $dbname) or $error = 1;
- }
- catch(Exception $ex){
- print("Error connecting to database: ". $ex->getMessage()) and die();
- }
-
- $method = $_SERVER['REQUEST_METHOD'];
- switch($method){
- case "GET":
- $sql = "SELECT * FROM noticias";
- $path = explode('/', $_SERVER['REQUEST_URI']);
- if(isset($path[3]) && is_numeric($path[3])) {
- $sql .= " WHERE id = :id";
- $stmt = $conn->prepare($sql);
- $stmt->bindParam(':id', $path[3]);
- $stmt->execute();
- $users = $stmt->fetch(PDO::FETCH_ASSOC);
- } else {
- $stmt = $conn->prepare($sql);
- $stmt->execute();
- $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
- }
-
- echo json_encode($users);
- break;
-
- case "POST":
- $user = json_decode(file_get_contents('php://input') );
- $sql = "INSERT INTO noticias(id, title, subject, created_at) VALUES(null, :title, :subject, :created_at)";
- $stmt = $conn->prepare($sql);
- $created_at = date('Y-m-d');
- $stmt->bindParam(':title', $user->title);
- $stmt->bindParam(':subject', $user->subject);
- $stmt->bindParam(':created_at', $created_at);
-
- if($stmt->execute()) {
- $response = ['status' => 1, 'message' => 'Record updated successfully.'];
- } else {
- $response = ['status' => 0, 'message' => 'Failed to update record.'];
- }
- echo json_encode($response);
- break;
-
- case "PUT":
- $user = json_decode( file_get_contents('php://input') );
- $sql = "UPDATE noticias SET title= :title, subject = :subject, updated_at = :updated_at WHERE id = :id";
- $stmt = $conn->prepare($sql);
- $updated_at = date('Y-m-d');
- $stmt->bindParam(':title', $user->title);
- $stmt->bindParam(':subject', $user->subject);
- $stmt->bindParam(':updated_at', $updated_at);
-
- if($stmt->execute()) {
- $response = ['status' => 1, 'message' => 'Record updated successfully.'];
- } else {
- $response = ['status' => 0, 'message' => 'Failed to update record.'];
- }
- echo json_encode($response);
- break;
-
- case "DELETE":
- $sql = "DELETE FROM noticias WHERE id = :id";
- $path = explode('/', $_SERVER['REQUEST_URI']);
-
- $stmt = $conn->prepare($sql);
- $stmt->bindParam(':id', $path[3]);
- if($stmt->execute()) {
- $response = ['status' => 1, 'message' => 'Record deleted successfully.'];
- } else {
- $response = ['status' => 0, 'message' => 'Failed to delete record.'];
- }
- echo json_encode($response);
- break;
- }
- ?>
|