Search code examples
phpmysqlpdobindvalue

How bindValue on primary key?


Is it recommended to bindValue on a primary key?

primary key value come from database result.

Note: It is not linked with GET/POST query.

For example:

$SQL2 = "SELECT storeID FROM orders limit 1"
$q = $db->prepare($SQL);
$q->execute();
$row = $q->fetch(PDO::FETCH_ASSOC);

$PrimaryKey = $row['storeID'];

$SQL2 = "SELECT * FROM store WHERE storeID= :storeID"
$q2 = $db->prepare($SQL);
$q2->bindValue(":storeID", $PrimaryKey);

Solution

  • It is more of a personal preference. In situations like the above, when you that the data type of the result is integer like PK or other int value, I never do bindValue but directly concatenate, eg:

    $sql = 'SELECT * FROM store WHERE storeID=' . $row['storeID'];

    $result = $db->prepare($sql)->execute()->fetch(PDO::FETCH_ASSOC);

    Just because its shorter and probably bit faster. But don't bother with such premature micro optimizations, if you have the practice of always using bindValue, it will not affect your performance at all. However if it looks cleaner to you to have it concatenated, there is no security flaw in those situations, so go for it.