My first attempt at PDO statements - Is this code actually correct and doing what it should?

StackOverflow https://stackoverflow.com/questions/21682403

  •  09-10-2022
  •  | 
  •  

Question

I'm brand new to PDO statements, and this is my very first attempt. I'm not completely sure if the code I have produced is achieving anything?

Am I protected from coding-genius-hackers?

<?php
$host   = "localhost";
$db = "test";
$user   = "root";
$pass   = "admin";

$who = '65';

$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);

$sql = "SELECT 

        tbl_tracking.id as trackID,
        tbl_tracking.from_user as trackFROM,
        tbl_tracking.viewed as trackVIEWED,
        tbl_tracking.date as trackDATE,

        tbl_users.id as usrID, 
        tbl_users.name as usrNAME,

        tbl_photos.profile as photosPROFILE,
        tbl_photos.photo_link as photoLINK,
        tbl_photos.default_photo as photoDEFAULT  

        FROM tbl_tracking 
        LEFT JOIN tbl_users ON tbl_tracking.from_user = tbl_users.id 

        LEFT JOIN tbl_photos ON tbl_photos.profile = tbl_users.id 

        WHERE tbl_tracking.viewed = '$who' AND tbl_photos.default_photo IS NULL OR tbl_photos.default_photo = '1'
        GROUP BY tbl_tracking.from_user
        ORDER BY tbl_tracking.id DESC
        LIMIT 9
        ";
$q   = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo '<a href="../profile/index.php?user=' . $r['usrID'] . '"><img src="../assets/uploads/thumbnail_' . $r['photoLINK'] . '" class="suggestUser" /></a>';
}
?>
Was it helpful?

Solution

To be protected against sql injection, you must use PDO's new of verifying values: binding parameters. This needs that your prepare statements instead of running them directly:

$q   = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that

Change your where clause:

WHERE tbl_tracking.viewed = :who AND tbl_photos.default_photo IS NULL OR tbl_photos.default_photo = '1'

then bind the value to your statement and execute it:

$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->execute();

or you can execute it directly with an array of values:

$q->execute(array(':who' => $who));

otherwise, I'm not very sure what your code should be doing, so I can't really tell if it will, but if your sql worked before using PDO, it should work now too.

For your code to be prone to sql injection, one of the values in your query must have a way to come from user-input, and it must be passed as-is to PDO's prepare(). Since we use a parameter :who instead of $who, there's no way your sql will be prepared with dangerous values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top