Home > OS >  Is this crud pdo correct?
Is this crud pdo correct?

Time:01-17

I have a question about my PDO crud I'm very new to the php language. I want to start off with making a crud as I do that with all the language's I tried to learn. Please help me out with this one.

$host = "localhost";
$user = "root";
$password = "";
$database = "database";

$pdo = new PDO("mysql:host=$host;dbname=$database", "$user", "$password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function updatecrud($pdo, $id){
   $sql = "UPDATE users SET password='test' WHERE id='$id'";

   if ($pdo->query($sql) === TRUE) {
     echo "Record updated successfully";
   } else {
     echo "Error updating record: " . $pdo->error;
   }
}

function deletecrud($pdo, $id){
   $sql = "DELETE FROM users WHERE id='$id'";

   if ($pdo->query($sql) === TRUE) {
     echo "Record deleted successfully";
   } else {
     echo "Error deleting record: " . $pdo->error;
   }
}

function createcrud($pdo){
   $name = "w";
   $surname = "test";

   $sql = "INSERT INTO users (username, password) VALUES (?,?)";
   $stmt= $pdo->prepare($sql);
   $stmt->execute([$name, $surname]);
}

function readcrud($pdo){
   $sql = "SELECT id, username, password FROM users";
   $result = $pdo->query($sql);

   if ($result->num_rows > 0) {
   // output data of each row
       while($row = $result->fetch_assoc()) {
           echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["password"]. "<br>";
       }
   } else {
       echo "0 results";
   }
}


deletecrud($pdo, "0");

here u see the error:

enter image description here

Thank you in advance

Also, if u need any more code or smth please reply and I'll add it.

CodePudding user response:

Id column is an auto-increment column used from mysql for tables, starting from 1.

In your function you are sending a string which is 0 so there is no way that there is a record in your table with id = 0 since ids start from 1

Check your table and see the ids yourself that exist there but this line:

deletecrud($pdo, "0");

will never find a record to delete

  •  Tags:  
  • Related