PHP PDO
在本教程中,我们将学习PHP PDO。
什么是PDO?
PDO(PHP数据对象)是一个PHP扩展,用于通过编写相同的代码来访问和使用不同类型的数据库(如MySQL,Oracle等)。
它充当数据抽象层,有助于发布查询和获取数据,而与数据库无关。
如何使用PDO连接到数据库?
我们调用PDO构造函数来创建数据库连接。
//constants define('DB_DSN', 'mysql:host=localhost;dbname=mydb'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', 'root123'); try { //create pdo connection object $pdocon = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD); } catch (PDOException $e) { printf("Error: " . $e->getMessage()); die(); }
在上面的代码中,PDO构造函数采用三个参数,即dsn,用户名和密码。
DB_DSN包含数据源名称,其中包含两项,一个是数据库驱动程序名称,另一个是数据库名称。
DB_USERNAME和DB_PASSWORD分别保存数据库的用户名和密码。
在整个教程中,我们将使用$pdocon作为PDO对象。
如何获取PDO错误代码?
当错误发生时,我们使用errorCode()方法获取错误代码。
这些错误代码是标准的SQLSTATE代码。
$pdocon->errorCode();
如何获取PDO错误消息?
当错误发生时,我们使用errorInfo()方法获取错误消息。
此方法将返回一个数组。
该数组由三个元素组成。
第0个元素表示SQLSTATE代码。
第二个元素包含特定于数据库驱动程序的错误代码。
第3个元素包含特定于数据库驱动程序的错误消息。
$pdocon->errorInfo();
查询执行的类型
基本上有三种类型的查询执行。
没有结果集的查询执行:INSERT,UPDATE和DELETE之类的查询不返回结果集,仅告诉我们受影响的行数。
使用结果集执行查询:像SELECT这样的查询通常会返回结果集以及返回的行数。
多次执行查询:例如,通过传递不同的数据多次运行INSERT查询。
插入,更新和删除数据
为了插入,更新和删除数据,我们使用exec()方法,它返回受影响的行数。
在下面的示例中,我们执行INSERT查询。
//query $query = sprintf("INSERT INTO student (`studentid`, `name`, `branch`) VALUES ('s001', 'theitroad', 'CSE')"); //execute the query $affectedRows = $pdocon->exec($query); //number of rows affected printf("Inserted Rows: %d", $affectedRows); //this will print "Inserted Rows: 1"
在下面的示例中,我们执行UPDATE查询。
//query $query = sprintf("UPDATE student SET name = 'Alice' WHERE studentid = 's2015'"); //execute the query $affectedRows = $pdocon->exec($query); //number of rows affected printf("Updated Rows: %d", $affectedRows); //this will print "Updated Rows: 1"
在下面的示例中,我们执行DELETE查询。
//query $query = sprintf("DELETE FROM student WHERE studentid = 's101'"); //execute the query $affectedRows = $pdocon->exec($query); //number of rows affected printf("Deleted Rows: %d", $affectedRows); //this will print "Deleted Rows: 1"
选择数据
要选择数据,我们使用" query()"方法,该方法将结果集作为PDOStatement对象返回。
要知道返回的总行数,我们使用rowCount()
方法。
//query $query = sprintf("SELECT studentid, name, branch FROM student LIMIT 0,10"); //execute query $result = $pdocon->query($query); //total rows returned printf("Selected Rows: %d", $result->rowCount()); //loop through the results foreach ($result as $row) { printf("StudentID: %s Name: %s Branch: %s", $row['studentid'], $row['name'], $row['branch']); }
预处理语句
当我们知道同一查询将仅通过更改参数执行多次时,便使用预处理语句。
例如,对学生表的INSERT查询将始终具有相同的模板,并且仅插入数据将发生更改。
如何创建预处理语句?
我们使用" prepare()"方法创建一个准备好的语句。
它用于准备执行查询。
$stmt = $pdocon->prepare($query);
如何执行预处理语句?
我们使用execute()
方法执行预处理语句。
此方法采用包含占位符和值的数组参数。
在下面的示例中,我们将看到这一点。
如何获得受影响的行总数?
为了获得受影响的行的总数,我们使用rowCount()
方法。
使用预处理语句更新数据
在以下示例中,我们执行一个UPDATE查询,该查询具有两个占位符:name
和:studentid
。
当执行准备好的语句时,我们使用包含占位符和值的数组调用execute()
方法。
//query $query = sprintf("UPDATE student SET name = :name WHERE studentid = :studentid"); //prepare the statement $stmt = $pdocon->prepare($query); //execute the prepared statement $stmt->execute(array( ":name" => "Alice", ":studentid" => "s101" )); //affected rows printf("Updated Rows: %d", $stmt->rowCount());
绑定参数
这是在查询中为占位符赋值的另一种方法。
我们使用bindParam()
并传递占位符,值和数据类型。
以下是可以传递给bindParam()方法的一些数据类型的列表。
- PDO :: PARAM_BOOL用于布尔数据
- PDO :: PARAM_INT用于整数数据
- PDO :: PARAM_STR用于字符串数据
- PDO :: PARAN_NULL用于空数据
$stmt->bindParam(":name", $name, PDO::PARAM_STR);
使用bind参数更新数据
//query $query = sprintf("UPDATE student SET name = :name WHERE studentid = :studentid"); //prepare the statement $stmt = $pdocon->prepare($query); //bind parameter $name = "Alice"; $studentid = "101"; $stmt->bindParam(":name", $name, PDO::PARAM_STR); $stmt->bindParam(":studentid", $studentid, PDO::PARAM_STR); //execute the prepared statement $stmt->execute(); //affected rows printf("Updated Rows: %d", $stmt->rowCount());
检索数据
我们可以使用两种方法" fetch()"和" fetchAll()"来检索数据。
在下面的示例中,我们使用fetch()方法从学生表中检索数据。
我们将参数" PDO :: FETCH_ASSOC"传递给fetch()方法。
这将使该方法以关联数组的形式返回结果。
//query $query = sprintf("SELECT studentid, name, branch FROM student LIMIT 0,10"); //execute the query $stmt = $pdocon->query($query); //returned rows printf("Selected Rows: %d", $stmt->rowCount()); //loop through the result while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { printf("StudentID: %s Name: %s Branch %s", $row['studentid'], $row['name'], $row['branch']); }
在下面的示例中,我们使用fetchAll()方法并传递参数PDO :: FETCH_ASSOC
以获取关联数组作为结果。
//query $query = sprintf("SELECT studentid, name, branch FROM student LIMIT 0,10"); //execute the query $stmt = $pdocon->query($query); //returned rows printf("Selected Rows: %d", $stmt->rowCount()); //get the result $result = $stmt->fetchAll(PDO::FETCH_ASSOC); //loop through the result foreach ($result as $row) { printf("StudentID: %s Name: %s Branch %s", $row['studentid'], $row['name'], $row['branch']); }
如何开始事务?
要开始事务,我们使用beginTransaction()
方法。
$pdocon->beginTransaction();
如何进行事务?
要提交事务,我们使用commit()
方法。
$pdocon->commit(); </pre></code> <h2>How to rollback?</h2> <p>To perform rollback we use the <code>rollback()</code> method. </p> <pre><code>$pdo->rollback();