Home Backend Development PHP Problem How to use pdo method to implement query in php

How to use pdo method to implement query in php

Apr 19, 2023 am 09:15 AM

PHP is a widely used server-side scripting language. It has many frameworks and libraries for developers to use, and PDO (PHP Data Object) is an extension of PHP to connect to the database, making it more convenient for developers. It can operate different types of databases efficiently, and also provides a safer way to avoid security issues such as SQL injection. This article will focus on how to use PDO to implement database queries.

1. Introduction to PDO

PDO is a database extension introduced in PHP 5.1. It is a lightweight, cross-platform data access layer. It provides standardized access to various databases, as well as support for data preprocessing and parameterized queries, thereby reducing the risk of security vulnerabilities and making our code more robust.

2. Establish a database connection

Before using PDO for database query, we need to establish a connection with the database first. The connection requires the user name, password, host name, port number, database name and other parameters of the database. Finally, a PDO object is obtained, and we can use this object for subsequent operations.

//Connect to the database
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$username = "root";
$password = " 123456";
try {

$pdo = new PDO($dsn, $username, $password);
echo "连接成功!";
Copy after login

} catch (PDOException $e) {

echo "连接失败:" . $e->getMessage();
Copy after login

}

In the above code, $dsn is the data source name, where Contains hostname, database name, and character set. $username and $password are the username and password required to connect to the database. If the connection is successful, "Connection successful!" will be output; if the connection fails, an error message will be output.

3. Basic query operations

Let’s introduce some basic PDO database query operations.

1. Query a single field

When we want to query a field in the database, we can use the following code:

//Query a single field
$sql = "SELECT count(*) FROM user WHERE status=1";
$res = $pdo->query($sql);
$row = $res->fetch(PDO::FETCH_NUM) ;
$count = $row[0];
echo "Number of users:" . $count;

In the above code, $sql is the SQL statement to be executed, $pdo-> ;query($sql) executes the statement and saves the result in $res. We can get the first row of data in the result set through $res->fetch(PDO::FETCH_NUM). PDO::FETCH_NUM means returning a numeric index. The returned array is accessed in numeric index mode, which facilitates us to obtain a single field. value.

2. Query multiple fields

When we need to query multiple fields, we can use the following code:

//Query multiple fields
$sql = "SELECT id, username, email FROM user WHERE status=1";
$res = $pdo->query($sql);
while ($row = $res->fetch(PDO:: FETCH_ASSOC)) {

echo "ID:" . $row['id'] . ",姓名:" . $row['username'] . ",邮箱:" . $row['email'] . "<br/>";
Copy after login
Copy after login

}

In the above code, $res->fetch(PDO::FETCH_ASSOC) will return an associative array, where the keys of the array represent the field names, and the array The value of is the value corresponding to this field.

3. Query multi-row data

When we need to query multi-row data, we can use the following code:

//Query multi-row data
$sql = "SELECT * FROM user WHERE status=1";
$res = $pdo->query($sql);
$list = $res->fetchAll(PDO::FETCH_ASSOC);
foreach ($list as $row) {

echo "ID:" . $row['id'] . ",姓名:" . $row['username'] . ",邮箱:" . $row['email'] . "<br/>";
Copy after login
Copy after login

}

In the above code, $res->fetchAll() returns all result set data. The fetchAll() method uses the PDO::FETCH_ASSOC parameter to convert the result set into an associative array array, and uses the foreach statement to traverse the array and output the data.

4. Use parameterized query

If we directly use the value entered by the user as part of the SQL statement in the query operation, it may cause security issues such as SQL injection. In order to avoid this Question, we can use parameterized queries. The following example shows how to use parameterized query:

//parameterized query
$username = "admin";
$password = "123456";
$sql = 'SELECT * FROM user WHERE username = ? AND password = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$username, $password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {

echo "用户名或密码错误!";
Copy after login

} else {

echo "欢迎," . $user['username'] . "!";
Copy after login

}

In the above code, we use the prepare() method to process the SQL statement, and then use the execute() method to pass the parameters into the query. The $stmt->fetch() method fetches data from the result set. This approach avoids SQL injection issues that arise from having multiple query parameters.

4. Summary

This article introduces how to use PDO to implement database queries. By learning basic operations such as connecting to the database, querying a single field, querying multiple fields, querying multiple rows of data, and using parameterized queries, we can operate the database more flexibly and effectively improve development efficiency. In actual development, we also need to consider other security issues, such as SQL injection issues, strengthening parameter verification, filtering, etc. More care needs to be taken during the development process to ensure the security of the application.

The above is the detailed content of How to use pdo method to implement query in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

What is the purpose of mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

See all articles