Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this crud pdo correct?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading