Reputation:
Recently i started learning PDO, and i fetch a trouble to understand the behavior of bindValue and direct execute with array.
$statement = $db->prepare('SELECT * FROM category WHERE `category_name`=?');
$statement->bindValue(1, 'Swimwear'); // It's okey
$statement->execute();
//direct execute with array
$statement->execute(array('Swimwear')); // It's also okey
But the real problem is why i don't have to use like?
$statement->execute(array(1 => 'Swimwear')); // It's not okey, Not working
Upvotes: 0
Views: 80
Reputation: 211680
With PDO you have three ways of adding placeholder values.
You can add them in individually with bindValue
.
You can add them in a simple array.
You can add them with an associative array if you have named them.
So to get that style to work you need to add a name to the prepared statement and also to the array passed to execute
:
$statement = $db->prepare('SELECT * FROM category WHERE `category_name`=:category');
$statement->execute(array(':category' => 'Swimwear'));
There is no placeholder named 1
so this wasn't working.
The bindValue()
function takes 1-indexed values which is why the bindValue(1, 'Swimwear')
call works. This is an exception to the usual 0-indexed rule of programming.
To make it work with the associative style you'll need to call it this way:
$statement->execute(array(0 => 'Swimwear'));
Upvotes: 0
Reputation: 34800
$statement->execute(array(1 => 'Swimwear'));
does not work, because the value should be in index 0, not 1. When using this syntax, correct code would be:
$statement->execute(array(0 => 'Swimwear'));
Though I don't see any point using such complicated syntax over array('Swimwear')
.
Upvotes: 2