Home  >  Article  >  New operation of pdo in php

New operation of pdo in php

无忌哥哥
无忌哥哥Original
2018-06-28 13:43:272293browse

* 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 &#39;<h3>成功添加了&#39;.$stmt->rowCount().&#39;条记录</h3>&#39;;
} else {
    echo &#39;<h3>添加失败</h3>&#39;;
    print_r($stmt->errorInfo());
    exit();
}

//6. Destroy PDO objects

$pdo = null;
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn