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

Use of PDO::query() in PHP

autoload
Release: 2023-04-09 22:02:02
Original
3440 people have browsed it

  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   )
Copy after login
query    ( string $statement   , int $PDO::FETCH_COLUMN   , int $colno   )
Copy after login
query    ( string $statement   , int $PDO::FETCH_CLASS   , string $classname   , array $ctorargs   )
Copy after login
query    ( string $statement   , int $PDO::FETCH_INTO   , object $object   )
Copy after login
  • $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>";
}
Copy after login
输出:1 saber 100 
      2 acher 77 
      3 luncher 56 
      4 cooker 18 
      5 张三 66
Copy after login

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!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template