-4

I don't understand the difference between two following code block. The first block is longer than the second and I have to determine the type of $id => PDO::PARAM_INT, $name => PDO::PARAM_STR. The second is concise. Please help me understand the difference between them. Thank you so much.

$stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->bindValue(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $db->prepare("SELECT * FROM table WHERE id=:id AND name=:name");
$stmt->execute(array(':name' => $name, ':id' => $id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

Please let me know what should I use? I know that two above code blocks have the same result. But which way should i use?

Dao Tam
  • 503
  • 1
  • 3
  • 13

1 Answers1

0

The difference between the two is largely down to preference. Placing the parameters within the execute() call is a shorter way of doing the same thing as expressly binding the parameters via bindValue. bindParam acts slightly differently. Note that all variables submitted via execute() are treated as strings, no matter what.

The advantage of the longer method is that you get to force data types - which is considered good practice - and it also allows for easier NULL inserts. You can, with bindParam also work with the variable before execution as its value is only submitted at the exact moment of the execute() call.

Eamonn
  • 1,338
  • 2
  • 21
  • 53