search
HomeBackend DevelopmentPHP Problem[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 and password 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, where mysql: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-&gt ;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!

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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

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 Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

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 XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools