Jonathan Jonathan - 3 months ago 7
PHP Question

PHP prepared statement - what are parameter colon's used for?

I've seen many articles using colon's in front of named parameters, and a couple that do not use the colon. I just assume not use the colon, simply because it's one less keystroke and slightly easier to read.

It seems to be working fine for me, but I'm curious if there is something important I'm missing when it comes to the use of colon's?

For example, this works just fine:

function insertRecord ($conn, $column1, $comumn2) {
try {
$insertRecord = $conn->prepare('INSERT INTO Table1 (column1, column2)
VALUES(:column1, :column2)');
$insertRecord->execute(array(
'column1' => $column1,
'column1' => $column2
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
}


As opposed to most developers using this, which also works:

function insertRecord ($conn, $column1, $comumn2) {
try {
$insertRecord = $conn->prepare('INSERT INTO Table1 (column1, column2)
VALUES(:column1, :column2)');
$insertRecord->execute(array(
':column1' => $column1,
':column1' => $column2
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
}


Notice the colon's in the execute statement parameters.

I'd like to understand what the colon's are for.

Answer

Colons are required in the SQL statement, to indicate which identifiers are placeholders.

Colons in the execute() or bindParam() calls are optional. The documentation specifies them, but the implementation is clever enough to figure out what you mean if you leave them out (what else could you mean?).