Home> headlines> body text

New operation of pdo in php

无忌哥哥
Release: 2018-06-28 13:43:27
Original
2269 people have browsed it

* 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');
Copy after login

//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)";
Copy after login

//3. Create the PDO preprocessing object

$stmt = $pdo->prepare($sql);
Copy after login

/ /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();
Copy after login

//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);
Copy after login

//5. Perform new operations

if($stmt->execute()){ //rowCount():返回上一个SQL语句影响的行数 echo '

成功添加了'.$stmt->rowCount().'条记录

'; } else { echo '

添加失败

'; print_r($stmt->errorInfo()); exit(); }
Copy after login

//6. Destroy PDO objects

$pdo = null;
Copy after login
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!