试图将mysqli代码转换为pdo

时间:2015-04-24 19:19:55

标签: php mysql pdo mysqli

我有这个mysqli代码,我试图将它从mysqli转换为pdo。我在下面尝试了它但是在转换它时遇到了麻烦。有人可以帮忙吗?

<?php

require_once './config.php';
include './header.php';
include('db.php');
include('database.php');


if($_POST)
{



    mysqli_real_escape_string($connection,$_POST['amount']);
    $values = str_replace(' ','',$_POST['amount']);
    $values = str_replace('£','',$values);
    $values = explode('-',$values);
    $min = $values[0];
    $max = $values[1];
    $res = mysqli_query($connection,'select `Image`,`recipe_name`,`recipe_price` from recipe where `recipe_price` BETWEEN "'.$min.'" AND "'.$max.'"');
    $count  =   mysqli_num_rows($res);
    $HTML='';
    if($count > 0)
    {
        while($row=mysqli_fetch_array($res))
        {
            $Image       = $row['Image'];
            $recipe_name    = $row['recipe_name'];
            $recipe_price      = $row['recipe_price'];




            $HTML .= '<div>';
            $HTML .= '<br /><img src=images/'.$Image.">";
            $HTML .= 'Name: '.$recipe_name;
            $HTML .= '<br />Price: '.$recipe_price;
            $HTML .= '</div><br /><hr />';

        }
    }
    else
    {
        $HTML='No Recipes Found';
    }
}
else
{
    $min = 0;
    $max = 10;
    $HTML='';
}

?>

有人可以帮忙告诉我下面的代码我哪里出错吗?     

require_once './config.php';
include './header.php';
include('db.php');
include('database.php');


if($_POST && isset($_POST['amount'])){
$values = $_POST['amount'];

$values = ['£', '', $values];
$values = explode('-',$values);

$min = $values[0];
$max = $values[1];

$sql = "SELECT `recipe_name`, `recipe_price`,  `Image` FROM `recipe` WHERE `recipe_price` BETWEEN "'.$min.'" AND "'.$max.'"");

    $count = $stmt->fetchAll();
        if ($count->fetchColumn() > 0) {
}
while($row = $stmt->fetch(/* PDO::FETCH_ASSOC */)) {
    // do loop stuff
}



    echo $row['recipe']; {

        }

    else
    {

    }
else
{
    $min = 0;
    $max = 10;
    $HTML='';
}
?>

1 个答案:

答案 0 :(得分:2)

您需要致电prepareexecute来执行查询。你在如何设置$min$max时也犯了错误,你不必要地重写了这些错误。

$values = str_replace(array(' ', '£'), '', $_POST['amount']);
list($min, $max) = explode('-', $values);
$sql = "SELECT `recipe_name`, `recipe_price`,  `Image` 
        FROM `recipe` 
        WHERE `recipe_price` BETWEEN :min AND :max");
$stmt = $connection->prepare($sql);
$stmt->execute(array(':min' => $min, ':max' => $max));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($rows) > 0) {
    foreach ($rows as $row) {
        // do loop stuff
    }
} else {
    $min = 0;
    $max = 10;
    $HTML = '';
}