Gtker
Gtker

Reputation: 2257

Which is the correct way to use PDO in PHP?

One from here:

$sth->execute(array(':calories' => $calories, ':colour' => $colour));

The other from here:

/*** reassign the variables again ***/
$data = array('animal_id'=>4, 'animal_name' => 'bruce');

/*** execute the prepared statement ***/
$stmt->execute($data);

My question is: :key or key ?

Sorry I don't have the PHP environment here.

Upvotes: 2

Views: 164

Answers (4)

binaryLV
binaryLV

Reputation: 9122

I use the second way, i.e.,

$query = 'insert into user (username, password) values (:username, :password)';
$param = array('username' => $username, 'password' => $password);

$param for this example sometimes can be made as compact('username', 'password') - seems handy to me.

Upvotes: 0

Macmade
Macmade

Reputation: 54010

Both are valid, but you are encouraged to use the :key notation, as it can prevent some errors, if you name a variable with a reserved keyword, for instance...

Upvotes: 2

Michał Mech
Michał Mech

Reputation: 2055

Both ways are correct and both examples run correct.

You can read about that in manual (user comments): http://www.php.net/manual/en/pdostatement.execute.php#71929

Upvotes: 0

maid450
maid450

Reputation: 7486

I would definitely trust php.net more than phpro.org ;)

However, in the same php.net page:

An array of insert values (named parameters) don't need the prefixed colon als key-value to work.

Upvotes: 1

Related Questions