简体   繁体   English

如何将MySQL查询正确转换为PDO

[英]How do I properly convert a mySQL query to PDO

I am trying to convert a mySQL query to PDO. 我正在尝试将mySQL查询转换为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. mySQL查询能够提取4个类别,并在每个类别中提取并显示适当数量的条目。 The PDO conversion query is only pulling 3 categories, and no entries in any category PDO转换查询仅提取3个类别,而没有任何类别的条目

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. 我还想提供一些有关如何使用新代码限制SQL注入的公开性的投入。

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. 在我的查询中,我尝试了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. 如ShowDev所指出的,“ if($ stmt-> fetchColumn()> 0)”条件使计数前进到第二行,然后仅返回剩余的3条记录。

The link posted by ShowDev shows correct procedure for this type of query ShowDev发布的链接显示了此类查询的正确过程

get rid of if ($stmt->fetchColumn() > 0) condition 摆脱if ($stmt->fetchColumn() > 0)条件

for this useless message change to this 对于这个无用的消息更改为此

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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