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

How to create PDO correectly

I have following existing code which is vulnerable for SQL injections.

<?php  
 //fetch.php  
 $connect = mysqli_connect("localhost", "root", "", "project");  
 if(isset($_POST["row_id"]))  
 {  
      $query = "SELECT id,username,usertype,division,mobnum,userstatus,date(created_at) as created_at FROM users WHERE id = '".$_POST["row_id"]."'";  

      $result = mysqli_query($connect, $query);  
      $row = mysqli_fetch_array($result);  
      echo json_encode($row);  
 }  
 ?>

SO I need to change it to PDO. Here what I tried. But this is not working. Can anyone help me?

    <?php  
     //fetch.php  
     $connect = mysqli_connect("localhost", "root", "", "project");  
     if(isset($_POST["row_id"]))  
     {  
          $query = "SELECT id,username,usertype,division,mobnum,userstatus,date(created_at) as created_at FROM users WHERE id =?";  
          $stmt = $connect->prepare($sql);  
          $stmt->bind_param('".$_POST["row_id"]."', $id);
          $stmt->execute();
          $result = $stmt->get_result(); 
          $row = mysqli_fetch_array($result);  
          echo json_encode($row);  
     }  
     ?>

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

>Solution :

What you wrote uses mysqli, not PDO. The PDO code is:

$connect = new PDO('mysql:host=localhost;dbname=project', 'root', '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$query = "SELECT id,username,usertype,division,mobnum,userstatus,date(created_at) as created_at FROM users WHERE id = :id";  
$stmt = $connect->prepare($sql);
$stmt->bindParam(':id', $_POST['row_id']);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
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