In PHP, you can use the prepare method to perform PDO parameterized queries. This method will return a PDOStatement object, using syntax such as "prepare('SELECT login_oid FROM logged in WHERE user_id=...".
The operating environment of this article: Windows 7 system, PHP7.1, Dell G3 computer.
How to implement php pdo parameterized query?
PDO parameterized query prepare() php prevents SQL injection
Parameterized query in PDO mainly uses the prepare() method, and then this method will return a PDOStatement object, which is a SQL statement (not Know how to translate), at this time the SQL statement is only compiled, but not executed. After calling the method in PDOStatement, the SQL statement will be executed, as in the following example:
$sm = $db->prepare('SELECT login_oid FROM logined WHERE user_id=:user_id;'); $sm->bindValue(':user_id', $user_id, PDO::PARAM_INT); $sm -> execute();
Before execute() is executed, you can call bindValue( ) or bindParam() method to replace the parameters you specified in the previously prepared SQL statement. There are two ways to specify parameters in the SQL statement: ':name' and '?'. The former one is used in the above code. The latter method is:
$sm = $db->prepare('SELECT * FROM fruit WHERE calories < ?;'); $sm->bindValue(1, $calories, PDO::PARAM_INT); $sm->execute();
bindValue() has three parameters. The first specifies which parameter in the SQL statement is to be replaced, the second specifies the replaced value, and the third specifies the value. Type, the type corresponds to the following:
PDO::PARAM_BOOL
Boolean type
PDO::PARAM_NULL
NULL type
PDO::PARAM_INT
Integer type
PDO::PARAM_STR
String type such as CHAR, VARCHAR, string
PDO::PARAM_LOB
Resource class large objects, such as files, etc.
PDO::PARAM_STMT
I don’t know
PDO::PARAM_INPUT_OUTPUT
This seems to be an extended type
There is no real number type provided, which is very surprising .
Let’s talk about the execute() method. It can also do parameter substitution, but it will change the types of all values into string types, as follows
$sm = $db->prepare('SELECT * FROM fruit WHERE calories < ?;'); $sm->execute(array($calories));
Multi-parameter substitution is as follows
$sm = $db->prepare('SELECT * FROM fruit WHERE calories < ?, id < ?;'); $sm->execute(array($calories, $user_id));
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement php pdo parameterized query. For more information, please follow other related articles on the PHP Chinese website!