What does :
mean before id
in the example below? Is it necessary?
$sth->bindValue(':id', $id, PDO::PARAM_INT);
Can I say :id
is a variable?
If PDO::PARAM_INT
is not necessary, why would I need to use it?
What does :
mean before id
in the example below? Is it necessary?
$sth->bindValue(':id', $id, PDO::PARAM_INT);
Can I say :id
is a variable?
If PDO::PARAM_INT
is not necessary, why would I need to use it?
:id
is a named placeholder for the prepared query. Somewhere else in your code there's a query along the lines of:
SELECT stuff FROM something WHERE id = :id
that gets run through PDO's prepare
function.
If
PDO::PARAM_INT
is not necessary, why would I need to use it?
Safety / data consistency. See PDO::PARAM_INT is important in bindParam?
What does : mean before id in the example below? Is it necessary?
Nothing particular. It's just a syntax. Like a $ sign in front of a php variable. It is necessary in the query, to let the parser to distinguish a placeholder from any other query part. And so it makes sense to use exactly the same name in bindValue()
Can I say :id is a variable?
Pretty much yes. By the meaming it is a variable, but to make it not confused with php variables it is called "a placeholder".
If PDO::PARAM_INT is not necessary, why would I need to use it?
It has absolutely nothing to do with security. You may want to use this modifier only to tell a database that you are sending an integer. Speaking for mysql, this database is quite tolerant to the data types, and almost anywhere you may omit the type modifier - in this case the data will be bound as string. You may want to set it explicitly quite seldom: only if you are using a placeholder in LIMIT clause or when sending a bigint value involved in a math.
What does
:
mean before id in the example below? Is it necessary?
$sth->bindValue(':id', $id, PDO::PARAM_INT);
Yes it is necessary. In PDOStatement::bindValue is defined that :id
is a named-placeholder of your parameter-identifier. If you were using question mark placeholders, your parameter-identifier would be 1
.
The form of your named placeholder has to be like :id
. If your named placeholder does not have that form then this leads to error.
WHERE id = ::id
Can I say :id is a variable?
No, :id
is your parameter-identifier
If PDO::PARAM_INT is not necessary, why would I need to use it?
Declaring the expected data type is a good safety tactic (not that you can rely on this only for safety of course). In case you use PDOStatement::bindParam you can define the length of the data type to add more safety.