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.
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)
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);
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.