bart2puck
bart2puck

Reputation: 2522

mysql prepared statements which statement i should use

Is there any major difference between the following prepared statements? Which one is more preferred, if so why?

1:

$stmt = $db->prepare("INSERT INTO users(userName) VALUES (:user)");
$user = "Steve";
$stmt->bindParam(':user', $user);
$stmt->execute();

2:

$stmt2 = $db->prepare('INSERT into users(userName) VALUES(:user)');
$stmt2->execute(array(':user'=>'Steve'));

Upvotes: 1

Views: 36

Answers (1)

N.B.
N.B.

Reputation: 14071

bindParam takes a variable parameter as a reference. That means variable value MIGHT be modified, depending on what you did (like invoked a stored procedure that alters value of variables passed to it).

That's why you should be using bindValue instead, unless you expect MySQL to alter the value of your variable.

Only actual MAJOR difference is that you cannot specify the variable type if you use your second scenario. Every parameter is treated as a string, while when using bindParam / bindValue, you have the freedom to define whether the parameter is a string or integer.

So what you should use then? Well, neither is wrong. If you find it easier to use second approach while inserting a lot of string data, then there's nothing wrong with it.

Upvotes: 4

Related Questions