I have been using the following style code:
$query = "INSERT INTO contact_messages (fromEmail, message) VALUES (:fromEmail, :message)";
// Create bound values
$query_params = array(
':fromEmail' => $contactFrom,
':message' => $contactMessage
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$return['messageSent'] = true;
}
catch(PDOException $ex)
{
die
}
I thought that this was safe, but just seen i haven't specified that i am binding the parameters? or is what im doing still safe enough?
Also at this point, should I still be using eg htmlPurifier on the input? or is the PDO bound parameters enough?
Yes it is still safe but binding parameter is safer.
The difference is when you pass the array to execute()
all the params are treated as strings.
Whereas when you bind params you are being explicit meaning there is no way to execute with the wrong data type.
bindParam
is used to pass a reference of the variable to the placeholders. bindParam
is useful when you run through a foreach loop like:
foreach ($params as $key => &$val)
{
$sth->bindParam($key, $val);
}
Notice the ampersand at &$val
. If you change the variable value after that code, the query will include the new value when you issue execute
whereas when you use bindValue
you pass by value directly to the placeholder you've specified in your query so modifying the variable won't affect it anymore.
Also, the way you're doing it directly in execute
is the same thing as bindValue
, which means that you're passing by value. The only difference is that you can call bindValue
and do something before you execute your query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.