Home  >  Article  >  Backend Development  >  Parsing PDO::Statement in PHP

Parsing PDO::Statement in PHP

autoload
autoloadOriginal
2021-04-23 10:38:252097browse

  Parsing PDO::Statement in PHP

        PHP We often need to connect to the database to add, delete, modify, and check data. Previously, we generally used mysqli## to operate the database. # connection method, but as the advantages of PDO gradually emerge, the connection method of PDO has become mainstream. This article will take you to take a look and use PDOThe Statement object returned after connection.

1. Database used

CREATE TABLE `fate` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `fate` VALUES ('1', 'saber', '100'),
('2', 'acher', '77'),
('3', 'luncher', '56'),
('4', 'cooker', '18')

2. Obtain Statement object:

<?php
$servername = "localhost";//数据库主机名
$username = "root";//用户名
$password = "root123456";//密码
$dbname   = "my_database";//数据库名称
 
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    echo "连接成功"."<br>"; 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "select * from fate";
    $statement = $conn->query($sql);
   }
catch(PDOException $e)
{
    echo $e->getMessage();
}
?>

3. Statement’s more commonly used attributes

    ##PDOStatement::bindColumn — Bind a column to a PHP Variable
  • PDOStatement::bindParam — Binds a parameter to the specified variable name
  • PDOStatement::columnCount — Returns the number of columns in the result set
  • PDOStatement::execute — Execute a prepared statement
  • PDOStatement::fetch — Get the next row from the result set
  • PDOStatement::fetchAll — Returns an array containing all rows in the result set
  • PDOStatement::fetchObject — Gets the next row and returns it as an object.
  • PDOStatement::rowCount — Returns the number of rows affected by the previous SQL statement
  • PDOStatement::setAttribute — Sets a statement attribute
  • PDOStatement::setFetchMode — Set the default fetch mode for a statement.
Recommended:

2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of Parsing PDO::Statement in PHP. For more information, please follow other related articles on the PHP Chinese website!

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