In PHP applications, operations that require modification of the database are one of the common requirements. PHP Data Object (PDO) provides a safe and efficient way to operate on relational databases.
This article will introduce how to use PDO extension to connect to MySQL database, and demonstrate through examples how to use PDO to modify database data.
Connecting to MySQL database
Before using PDO, you first need to connect to the database. The following is a sample code for connecting to a MySQL database:
//数据库连接参数 $host = 'localhost'; $dbname = 'test'; $username = 'root'; $password = ''; //连接数据库 try { $db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); } catch(PDOException $e) { echo $e->getMessage(); }
In the above code, we connect to the database through the constructor of the PDO class. First, specify the host name and database name of the MySQL database, and then pass in the user name and password to connect.
Modify database data
After the connection is successful, let’s look at how to use PDO to modify database data. We assume there is a student table containing id, name and age fields. Next, we will demonstrate how to use PDO to modify data on this table.
- Update a single field
We can use PDO's prepare() function to perform modification operations. The following is a code example for updating the record with id 1 in the student table:
//更新数据 $id = 1; $newName = 'Tom'; $sql = "UPDATE student SET name=:name WHERE id=:id"; $stmt = $db->prepare($sql); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->bindParam(':name', $newName, PDO::PARAM_STR); $stmt->execute();
In the above code, we first define the id and new name value of the record to be updated. We then update name to $newName via the UPDATE statement, where :id and :name are placeholders. Next, we use PDO's prepare() function to prepare the SQL statement and bind the values of $id and $newName through the bindParam() function. Finally, we call the execute() function to perform the update operation.
- Update multiple fields
If you want to update multiple fields, we can use a method similar to the above. The following is a code example that updates the name and age fields of the record with id 1 in the student table:
//更新数据 $id = 1; $newName = 'Tom'; $newAge = 20; $sql = "UPDATE student SET name=:name, age=:age WHERE id=:id"; $stmt = $db->prepare($sql); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->bindParam(':name', $newName, PDO::PARAM_STR); $stmt->bindParam(':age', $newAge, PDO::PARAM_INT); $stmt->execute();
In the above code, we update name and age to new values through the UPDATE statement. Note that we need to bind corresponding parameters for each field to be updated.
- Batch update records
If we want to update data in batches, we can use the transaction function of PDO. The following is a code example for updating multiple student records:
//更新多条数据 $students = array( array('id'=>1, 'name'=>'Tom', 'age'=>20), array('id'=>2, 'name'=>'Jack', 'age'=>22), array('id'=>3, 'name'=>'Lily', 'age'=>21) ); try { $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->beginTransaction(); $sql = "UPDATE student SET name=:name, age=:age WHERE id=:id"; $stmt = $db->prepare($sql); foreach ($students as $student) { $stmt->bindParam(':id', $student['id'], PDO::PARAM_INT); $stmt->bindParam(':name', $student['name'], PDO::PARAM_STR); $stmt->bindParam(':age', $student['age'], PDO::PARAM_INT); $stmt->execute(); } $db->commit(); } catch (PDOException $e) { $db->rollback(); echo $e->getMessage(); }
In the above code, we define an array $students that contains the records to be updated. Then, we implemented the transaction operation by using the beginTransaction() function and the commit() function. In the loop, we bind the id, name and age parameters of each record and execute the SQL statements respectively.
Summary
Using PDO to modify database data is a safe and reliable method. In this article, we explain how to use PDO to connect to the MySQL database, and demonstrate through examples how to use PDO to modify database data. It is worth mentioning that we also introduced how to use the transaction function of PDO to update records in batches, which is a very practical skill.
The above is the detailed content of How to use PHP PDO extension to connect to MySQL database. 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

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
