简体   繁体   中英

How do I properly convert a mySQL query to PDO

I am trying to convert a mySQL query to PDO.

I have partly got the data coming through as expected but I cannot get the entire query to pull the correct data. The mySQL query is able to pull 4 categories with the appropriate number of entries in each category being pulled and displayed. The PDO conversion query is only pulling 3 categories, and no entries in any category

I am assuming I have not converted the query correctly but I cannot find where the issue is.

I would also like some input on how to limit exposure to SQL injection with the new code.

OLD QUERY (Working)

function listPuppies(){

    include("db_connect.php");

    $query = "  SELECT *
                FROM tblLitters
                WHERE available = 1
                ORDER BY litBreed, litMother";
    $resultOut = mysql_query($query, $connection) or die ("<br>Error in query: $query.".mysql_error($connection));

    //Check if a row is returned
    if (mysql_num_rows($resultOut) > 0) {

        while($rowOut = mysql_fetch_array($resultOut)){

            $litterID           = $rowOut['litterID'];
            $litMother          = $rowOut['litMother'];
            $litBreed           = $rowOut['litBreed'];
            $litBreedDate       = $rowOut['litBreedDate'];
            $litDesc            = $rowOut['litDesc'];
            $litterImage        = $rowOut['litImage'];
            $litterImageThumb   = $rowOut['litterImageThumb'];
            $litBreedCost       = $rowOut['litBreedCost'];

            if ($litterImageThumb == ''){
                $litterPic = "";
            }else{
                $litterPic = "<img src=\"images/Litters/".$litterImageThumb."\" align=\"right\" style=\"padding:1px; margin:3px; border:6px solid #fff;\">";
            }

            echo "<table width=\"650\"><tr>\n";
            if ($breed <> $rowOut['litBreed']){
                $breed = $rowOut['litBreed'];
                echo "</tr></table>\n";
                echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\">\n";
                echo "<br><table width=\"650\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\">&nbsp;</td></tr>";
                $counter = 0;
            }else{
                if ($pupLitterID <> $rowOut['litterID']){
                    echo "</table>\n";
                    echo "<br><br><br><table width=\"650\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\">&nbsp;</td></tr>";
                    $counter = 0;
                }
            }





            $query = "  SELECT *
                        FROM tblPuppies
                        WHERE litterID = $litterID";
            $result = mysql_query($query, $connection) or die ("<br>Error in query: $query.".mysql_error($connection));

            //$breed = $row['pupBreed'];
            $counter = 0;



            //Check is a row is returned
            if (mysql_num_rows($result) > 0) {

                //old table start
                while($row = mysql_fetch_array($result)){
                    $status = $row['pupStatus'];
                    $pupLitterID = $row['litterID'];

                    if ($status == "For Sale"){
                        if ($row['pupOnHold'] == 1){
                            $status = '<font color=\"red\">On Hold</font>';
                        }
                        if ($row['pupSold'] == 1){
                            $status = '<font color=\"red\">Sold</font>';
                        }
                    }
                    if ($row['pupSex'] == 'F'){
                        $sex = 'Female';
                    }else{
                        $sex = 'Male';
                    }

                    //used to change popup window position depending on where thumbnail is palced on page
                    if ($counter == 0){
                        echo "<td width=\"33%\"><a class=\"thumbnailLeft\" href=\"#thumb\">";
                    }
                    if ($counter == 1){
                        echo "<td width=\"33%\"><a class=\"thumbnail\" href=\"#thumb\">";
                    }
                    if ($counter == 2){
                        echo "<td width=\"33%\"><a class=\"thumbnailRight\" href=\"#thumb\">";
                    }
                    echo "<div align=\"center\"><img src=\"images/ForSale/".$row['pupPicThumb']."\" style=\"padding:1px; border:6px solid #fff;\"><br>".$row['pupName']." - $sex<br><strong>$status</strong></div><span><img src=\"images/ForSale/".$row['pupPic']."\"></span></a><div align=\"center\"><a href=\"mailto:sales@adorablepuppies.com.au?Subject=Interest in puppy ".$row['pupName']."\">Contact Us About This Pup</a></div></td>";

                    if ($counter == 2){
                        echo "</tr><tr>\n";
                        $counter = -1;

                        if ($breed <> $rowOut['litBreed']){
                            $breed = $rowOut['litBreed'];
                            echo "</table>\n";
                            echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\"><br>\n";
                            echo "<table width=\"95%\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Litter Birth Date: </strong>$litBreedDate<br><br></span></td></tr></table>";
                            echo "<table width=\"650\"><tr>\n";
                            $counter = -1;
                        }
                    }               
                    $counter = $counter + 1;                        
                }
                echo "</tr></table>\n";
            }else{
                echo "There are no puppies left for sale in this litter, sorry.<br><br>Please check back again soon.";
            }// End IF/ELSE 





        }//end outer while

    }else{
        echo "There are currently no puppies for sale.<br>Please check back again soon.";
    }//end outer if
}

NEW QUERY (Not Working entirely)

function listPuppies(){

include("db_connect.php");

    try {
$stmt = $connection->prepare("SELECT * FROM tblLitters WHERE available = 1");
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$stmt->execute();
}

//Catch PDO Query Error
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}

// set the resulting array to associative
//$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->fetchColumn() > 0) {

    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $rowOut){

            $litterID           = $rowOut['litterID'];
            $litMother          = $rowOut['litMother'];
            $litBreed           = $rowOut['litBreed'];
            $litBreedDate       = $rowOut['litBreedDate'];
            $litDesc            = $rowOut['litDesc'];
            $litterImage        = $rowOut['litImage'];
            $litterImageThumb   = $rowOut['litterImageThumb'];
            $litBreedCost       = $rowOut['litBreedCost'];

            if ($litterImageThumb == ''){
                    $litterPic = "";
                }else{
                    $litterPic = "<img src=\"images/Litters/".$litterImageThumb."\" align=\"right\" style=\"padding:1px; margin:3px; border:6px solid #fff;\">";
                }

            echo "<table width=\"600\"><tr>\n";
            if ($breed <> $rowOut['litBreed']){
                $breed = $rowOut['litBreed'];
                echo "</tr></table>\n";
                echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\">\n";
                echo "<br><table width=\"600\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\">&nbsp;</td></tr>";
                $counter = 0;
            }else{
                if ($pupLitterID <> $rowOut['litterID']){
                    echo "</table>\n";
                    echo "<br><br><br><table width=\"600\" cellspacing=\"0\" cellpadding=\"5\"><tr><td colspan=\"3\"><table bgcolor=\"#044726\" width=\"100%\" border=\"1\" bordercolor=\"#137b48\" cellpadding=\"6\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Cost: </strong>$$litBreedCost<br><br></span></td></tr></table></td></tr><tr><td colspan=\"3\">&nbsp;</td></tr>";
                    $counter = 0;
                }
            }

            $stmt1 = $connection->prepare("SELECT * FROM tblPuppies WHERE litterID = .$litterID.");

            $counter = 0;

            //Check if a row is returned
            if ($stmt1->fetchColumn() > 0) {

                //old table start
                foreach ($stmt1->fetch(PDO::FETCH_ASSOC) as $rowOut){
                    $status = $row['pupStatus'];
                    $pupLitterID = $row['litterID'];

                    if ($status == "For Sale"){
                        if ($row['pupOnHold'] == 1){
                            $status = '<font color=\"red\">On Hold</font>';
                        }
                        if ($row['pupSold'] == 1){
                            $status = '<font color=\"red\">Sold</font>';
                        }
                    }
                    if ($row['pupSex'] == 'F'){
                        $sex = 'Female';
                    }else{
                        $sex = 'Male';
                    }

                    //used to change popup window position depending on where thumbnail is placed on page
                    if ($counter == 0){
                        echo "<td width=\"33%\"><a class=\"thumbnailLeft\" href=\"#thumb\">";
                    }
                    if ($counter == 1){
                        echo "<td width=\"33%\"><a class=\"thumbnail\" href=\"#thumb\">";
                    }
                    if ($counter == 2){
                        echo "<td width=\"33%\"><a class=\"thumbnailRight\" href=\"#thumb\">";
                    }
                    echo "<div align=\"center\"><img src=\"images/ForSale/".$row['pupPicThumb']."\" style=\"padding:1px; border:6px solid #fff;\"><br>".$row['pupName']." - $sex<br><strong>$status</strong></div><span><img src=\"images/ForSale/".$row['pupPic']."\"></span></a><div align=\"center\"><a href=\"mailto:sales@adorablepuppies.com.au?Subject=Interest in puppy ".$row['pupName']."\">Contact Us About This Pup</a></div></td>";

                    if ($counter == 2){
                        echo "</tr><tr>\n";
                        $counter = -1;

                        if ($breed <> $rowOut['litBreed']){
                            $breed = $rowOut['litBreed'];
                            echo "</table>\n";
                            echo "<br><br><div class=\"breedHead\">$breed's For Sale</div><hr color=\"#C5FBB4\"><br>\n";
                            echo "<table width=\"95%\"><tr><td>".$litterPic."<span style=\"font-size:12pt;\">".$litDesc."<br><br><strong>Mother:</strong> $litMother<br><strong>Litter Birth Date: </strong>$litBreedDate<br><br></span></td></tr></table>";
                            echo "<table width=\"600\"><tr>\n";
                            $counter = -1;
                        }
                    }               
                    $counter = $counter + 1;                        
                }
                echo "</tr></table>\n";
            }else{
                echo "There are no puppies left for sale in this litter, sorry.<br><br>Please check back again soon.";
            }// End IF/ELSE 





        }//end outer while

    }else{
        echo "There are currently no puppies for sale.<br>Please check back again soon.";
    }//end outer if
}

Thanks in advance

I found my issue for the entries in categories not showing.

Within my query I tried SELECT * WHERE field1 = .$variable.

But I needed to bind the variable as a parameter instead, like so:

$stmt1 = $connection->prepare("SELECT * FROM tblPuppies WHERE litterID = :litterID"); 
            $stmt1->bindParam(':litterID', $litterID);
            $stmt1->execute();

This successfully populated my categories as expected.

It is worth noting that Your Common Sense's answer was right, however only answered part of my question. anyone else reading these answers should take note of both answers.

EDIT......

As pointed out by ShowDev, the ' if ($stmt->fetchColumn() > 0)' condition advanced the count to the second row, and then only returned the remaining 3 records.

The link posted by ShowDev shows correct procedure for this type of query

get rid of if ($stmt->fetchColumn() > 0) condition

for this useless message change to this

$found = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($found) {
    foreach ($found as $rowOut){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM