PDO - query giving no results

亡梦爱人 提交于 2020-01-14 05:18:09

问题


This is my prepared statment.

SELECT `id`, `title`, `image`, `discount`, `price`, `new_price`, `img_url` FROM `deals` WHERE `active`="1" AND `category`=:ctid AND `img_url`!=""  AND `Brands`=:p1 ORDER BY `order`, `id` ASC LIMIT 0, 12;

This is the array that i am using in bindParam.

Array
(
    [:ctid] => 1
    [:p1] => Apple
)

Here's the PHP code:

$sql = 'SELECT `id`, `title`, `image`, `discount`, `price`, `new_price`, `img_url` FROM `deals` WHERE `active`="1" AND `category`=:ctid AND `img_url`!=""  AND `Brands`=:p1 ORDER BY `order`, `id` ASC LIMIT 0, 12;';
$sql = $link->prepare( $sql );

$binders = array(
  ':ctid' => 1,
  ':p1' => 'Apple'
);

foreach( $binders as $key => $value ) {
    $sql->bindParam( $key, $value );
}

$sql->execute();
$sql->setFetchMode( PDO::FETCH_ASSOC );
$result = $sql->fetchAll();

This gives no result.

But, if i do a direct query, i get results from the db. What could be wrong in the above query.

Any help is appreciated.


回答1:


The problem here is that you binding parameters with bindParam, which uses binding by reference. In your case you should use bindValue instead:

foreach( $binders as $key => $value ) {
    $sql->bindValue( $key, $value );
}

Or you can pass your array directly to execute() method:

$sql->execute( $binders );

As described in manual:

the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.

So when your foreach loop ends $value has value of last array item Apple. So when execute runs, both :ctid and :p1 values are becoming equal to Apple. Surely, this is not what you want)




回答2:


Try this to bindvalue

$sql = 'SELECT `id`, `title`, `image`, `discount`, `price`, `new_price`, `img_url` FROM `deals` WHERE `active`="1" AND `category`=:ctid AND `img_url`!=""  AND `Brands`=:p1 ORDER BY `order`, `id` ASC LIMIT 0, 12;';
$link->prepare($sql);
$link->execute([
    ':ctid' => 1,
    ':p1' => 'Apple'
]);
$result = $link->fetchAll(PDO::FETCH_ASSOC);


来源:https://stackoverflow.com/questions/25996358/pdo-query-giving-no-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!