Home  >  Article  >  Backend Development  >  Use of PDO::query() in PHP

Use of PDO::query() in PHP

autoload
autoloadOriginal
2021-04-23 14:09:303353browse

  Use of PDO::query() in PHP

    PHP We often need to connect to the database. In the past, the connection method of mysqli was generally used for database operations, but with the The advantages of PDO are gradually emerging, and the connection method of PDO has become mainstream. This article will take you to see how to use query after using PDO to connect to the database. ()Read the data.

First let’s take a look at the use of query():

query    ( string $statement   )
query    ( string $statement   , int $PDO::FETCH_COLUMN   , int $colno   )
query    ( string $statement   , int $PDO::FETCH_CLASS   , string $classname   , array $ctorargs   )
query    ( string $statement   , int $PDO::FETCH_INTO   , object $object   )
  • $statement: SQL statement that needs to be prepared and executed.

  • ##Return value: Return a PDOStatement object, or return false on failure.

Code example:

<?php

$type="mysql";
$servername="localhost";
$dbname="my_database";
$dsn="$type:host=$servername;dbname=$dbname";

$username="root";
$password="root123456";

$pdo=new PDO($dsn,$username,$password);
//错误模式,用于抛出异常
$pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);
$sql="select * from fate";
$statement =$pdo->query($sql);
foreach($statement as $row){
    echo $row[&#39;ID&#39;]," ";
    echo $row[&#39;NAME&#39;]," ";
    echo $row[&#39;AGE&#39;]," ";
    echo "<br>";
}
输出:1 saber 100 
      2 acher 77 
      3 luncher 56 
      4 cooker 18 
      5 张三 66

Recommendation: 2021 PHP Interview Questions Summary (Collection)》《php video tutorial

The above is the detailed content of Use of PDO::query() 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