* PDO preprocessing mainly uses the PDOStatement object
* This object is created through: $pdo->prepare() method
* Both read and write operations can be done through: $pdoStmt- >execute() method
* In addition to using the ? symbol, placeholders in preprocessed SQL statements can also use named parameters, such as: name:email...
* The following is an example of adding new data for demonstration. It is divided into 6 steps:
* 1. Connect to the database and create a PDO object
* 2. Prepare preprocessed SQL statements and placeholders Use named parameter format:
* 3. Create PDO preprocessing object: instance of PDOStatement
* 4. Bind parameters to SQL statement object, preprocessing object
* 5. Perform new operations (in PDO, use execute() for reading and writing)
* 6. Destroy PDO objects (optional)
//1. Connect to the database and create PDO Object
$pdo = new PDO('mysql:dbname=php', 'root', 'root');
//2. Prepare the preprocessing SQL statement. The placeholder uses the named parameter format:
$sql = "INSERT `user` SET `user_name`=:name, `email`=:email,`password`=sha1(:password)";
//3. Create the PDO preprocessing object
$stmt = $pdo->prepare($sql);
/ /View the generated SQL statement, which can be copied to the SQL command window and run to ensure the correctness of the statement
echo $stmt->queryString;exit();
//4. Bind parameters to the preprocessing object
$data = ['name'=>'杨过','email'=>'yg@php.cn', 'password'=>'123']; $stmt->bindParam(':name',$data['name'],PDO::PARAM_STR); $stmt->bindParam(':email',$data['email'],PDO::PARAM_STR); $stmt->bindParam(':password',$data['password'],PDO::PARAM_STR);
//5. Perform new operations
if($stmt->execute()){ //rowCount():返回上一个SQL语句影响的行数 echo '<h3>成功添加了'.$stmt->rowCount().'条记录</h3>'; } else { echo '<h3>添加失败</h3>'; print_r($stmt->errorInfo()); exit(); }
//6. Destroy PDO objects
$pdo = null;