


[Example sharing] PHP PDO operation database (add, delete, modify, check)
PHP PDO is an extension of PHP. It provides PHP developers with a standardized way to operate databases, allowing developers to seamlessly switch between different databases. This article will demonstrate how to use PHP PDO to connect to a MySQL database and write an example of adding, deleting, modifying, and checking code.
Install the PDO extension
Before you begin, make sure you have the PDO extension installed in your PHP environment. You can check whether PDO is already installed in your current environment by running the following command in the terminal.
php -m | grep pdo
If no error message is prompted, it means that PDO has been installed successfully. If the prompt does not find the PDO extension, please install the corresponding version of PDO according to your operating system and PHP version.
Connecting to MySQL database
Before the demonstration, we first need to create a MySQL database locally and create a new data table named test. At the same time, in order to connect to the database, we need to prepare the information necessary for the connection, such as database name, user name, password, etc. The connection code is as follows:
$dbname = 'test'; $username = 'root'; $password = ''; $dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8"; try { $pdo = new PDO($dsn, $username, $password); echo "连接成功"; } catch(PDOException $e) { echo $e->getMessage(); }
Description:
-
dbname
is the database name, which can be modified according to the actual situation; -
username
andpassword
are the username and password for accessing the database, which should be modified according to the actual situation; -
dsn
is the necessary parameter for PDO to connect to the MySQL database, wheremysql:host=localhost
is the host name of MySQL,dbname=$dbname
is the database name,charset=utf8
is the character set to ensure that our data is transmitted during transmission There will be no garbled characters.
If the connection is successful, the page will output "Connection successful".
Get data
Next, we will demonstrate how to use PDO to get data from the database. The code is as follows:
$sql = "SELECT * FROM test"; $stmt = $pdo->query($sql); while ($row = $stmt->fetch()) { echo $row['id'] . ' ' . $row['name'] . ' ' . $row['age'] . "<br>"; }
Description:
-
SELECT * FROM test
is a SQL statement, where test is the name of the data table we created; -
$stmt
is the result set object returned after PDO executes the SQL statement; -
$stmt->fetch()
is used to obtain a piece of data in the result set, After each execution of this method,$stmt
will point to the next piece of data; -
while
loop is used to traverse all qualified data records until the result set Until there is no data.
Add data
Next, we will demonstrate how to use PDO to add data to the database. The code is as follows:
$name = 'Tom'; $age = 28; $sql = "INSERT INTO test(name,age) VALUES(:name,:age)"; $stmt = $pdo->prepare($sql); $stmt->bindValue(':name', $name); $stmt->bindValue(':age', $age); $result = $stmt->execute(); if ($result) { echo "数据插入成功"; } else { echo "数据插入失败"; }
Description:
-
INSERT INTO
is a SQL statement used to insert new data into the data table; -
:name
and:age
are placeholders for PDO parameter binding and will be replaced with real values in the following code; -
$ pdo->prepare($sql)
is used to preprocess SQL statements, where$sql
is the SQL statement to be executed; -
$stmt-> ;bindValue(':name', $name)
Bind the placeholder:name
to the specific value$name
; -
$result = $stmt->execute()
Execute the SQL statement and return the execution result.
Update data
Next, we will demonstrate how to use PDO to update data in the database. The code is as follows:
$id = 1; $name = 'John'; $age = 30; $sql = "UPDATE test SET name=:name,age=:age WHERE id=:id"; $stmt = $pdo->prepare($sql); $stmt->bindValue(':name', $name); $stmt->bindValue(':age', $age); $stmt->bindValue(':id', $id); $result = $stmt->execute(); if ($result) { echo "数据更新成功"; } else { echo "数据更新失败"; }
Description:
-
UPDATE
is a SQL statement used to update data in the data table; -
SET name=:name,age=:age
indicates the field to be updated and the corresponding value; -
WHERE id=:id
indicates the conditions of the data to be updated; -
$stmt->bindValue(':id', $id)
Bind the placeholder:id
to a specific value$id
.
Deleting Data
Finally, we will demonstrate how to use PDO to delete data in the database. The code is as follows:
$id = 1; $sql = "DELETE FROM test WHERE id=:id"; $stmt = $pdo->prepare($sql); $stmt->bindValue(':id', $id); $result = $stmt->execute(); if ($result) { echo "数据删除成功"; } else { echo "数据删除失败"; }
Description:
-
DELETE FROM
is a SQL statement used to delete data from the data table; -
WHERE id=:id
Indicates the condition of the data to be deleted; -
$stmt->bindValue(':id', $id)
Change the placeholder:id
is bound to the specific value$id
.
Summary
The above is an example of using PHP PDO to operate the MySQL database to add, delete, modify, and query. I believe that through these examples, everyone has mastered the method of using PDO to connect to the database and perform related operations on the data. In actual projects, you can also combine other PHP frameworks and components to quickly develop some complex business logic.
The above is the detailed content of [Example sharing] PHP PDO operation database (add, delete, modify, check). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
