Home Backend Development PHP Tutorial Learn PHP PDO: How to use PDO to connect to the database and execute SQL statements

Learn PHP PDO: How to use PDO to connect to the database and execute SQL statements

Mar 19, 2024 pm 04:03 PM
php database pdo sql statement

学习PHP PDO:如何使用PDO连接数据库和执行SQL语句

Learn PHP PDO: How to use PDO to connect to the database and execute SQL statements

In PHP development, interacting with the database is a very common requirement. PHP PDO (PHP Data Objects) is a high-level abstract interface for database operations. It provides a universal method of accessing the database and can interact with various database systems, including MySQL, PostgreSQL, SQLite, etc.

This article will introduce how to use the PDO extension in PHP to connect to the database and execute SQL statements. We will first learn how to connect to the database and then learn how to perform SQL queries, inserts, updates, and delete operations.

1. Connect to the database

First, we need to create a PDO object to connect to the database. The following is a sample code to connect to the database:

<?php
$host = 'localhost';
$dbname = 'dbname';
$user = 'username';
$pass = 'password';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Database connection successful!";
} catch(PDOException $e) {
    echo "Database connection failed:" . $e->getMessage();
}
?>
Copy after login

In the above code, we first define the host name, database name, user name and password of the database. Then we use the PDO constructor to create a PDO object and set the error handling mode to throw an exception. If the connection is successful, "Database connection successful!" will be output. If the connection fails, specific information about the connection failure will be output.

2. Execute SQL query

Next, we will learn how to use PDO to perform SQL query operations. Here is a simple query example:

<?php
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);

while ($row = $stmt->fetch()) {
    echo $row['username'] . "<br>";
}
?>
Copy after login

In the above code, we define a SQL query statement, and then use the $pdo->query($sql) method to execute the query and store the results in$stmt variable. Then use the fetch() method to get the data row by row from the result set and output the user name.

3. Perform SQL insert, update and delete operations

In addition to query operations, PDO can also perform insert, update and delete operations. Here is a simple insert example:

<?php
$sql = "INSERT INTO users (username, email) VALUES ('john_doe', 'john@example.com')";
$pdo->exec($sql);
echo "User added successfully!";
?>
Copy after login

In the above code, we define an insert statement and then use the $pdo->exec() method to perform the insert operation. Finally output "User added successfully!".

In addition to insert operations, PDO can also perform update and delete operations. Here is a simple update example:

<?php
$user_id = 1;
$new_username = 'jane_doe';

$sql = "UPDATE users SET username = '$new_username' WHERE id = $user_id";
$pdo->exec($sql);
echo "Username updated successfully!";
?>
Copy after login

In the above code, we define an update statement and then use the $pdo->exec() method to perform the update operation. Finally output "Username updated successfully!".

The deletion operation is similar. Here is a simple deletion example:

<?php
$user_id = 1;

$sql = "DELETE FROM users WHERE id = $user_id";
$pdo->exec($sql);
echo "User deleted successfully!";
?>
Copy after login

In the above code, we define a delete statement and then use the $pdo->exec() method to perform the delete operation. Finally output "User deleted successfully!".

Summary

This article introduces how to use the PDO extension in PHP to connect to the database and execute SQL statements, including query, insert, update and delete operations. By learning PDO, you can interact with the database more efficiently and safely, avoiding security issues such as SQL injection. I hope this article is helpful to you, and I wish you better achievements in PHP development!

The above is the detailed content of Learn PHP PDO: How to use PDO to connect to the database and execute SQL statements. 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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

How to create tables with sql server using sql statement How to create tables with sql server using sql statement Apr 09, 2025 pm 03:48 PM

How to create tables using SQL statements in SQL Server: Open SQL Server Management Studio and connect to the database server. Select the database to create the table. Enter the CREATE TABLE statement to specify the table name, column name, data type, and constraints. Click the Execute button to create the table.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to judge SQL injection How to judge SQL injection Apr 09, 2025 pm 04:18 PM

Methods to judge SQL injection include: detecting suspicious input, viewing original SQL statements, using detection tools, viewing database logs, and performing penetration testing. After the injection is detected, take measures to patch vulnerabilities, verify patches, monitor regularly, and improve developer awareness.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

See all articles