How to operate database in PHP?
In web development, the database is a very important component. As a scripting language, PHP is ideal for writing code that interacts with databases. PHP provides a variety of ways to operate the database, including native MySQL functions, PDO, and higher-level ORM frameworks. In this article, we will explain how to work with databases in PHP.
- PHP interacts with MySQL
MySQL is a popular relational database management system and one of the most commonly used databases for PHP. PHP provides a series of native MySQL functions that can be used to connect to the MySQL database, query data, insert data, modify data and delete data. The following is a basic sample code to connect to a local MySQL database and query all data in the users table:
<?php // 连接 MySQL 数据库 $link = mysqli_connect("localhost", "username", "password", "database_name"); // 检查连接是否成功 if ($link === false) { die("Error: Could not connect. " . mysqli_connect_error()); } // 查询 users 表中的所有数据 $sql = "SELECT * FROM users"; if ($result = mysqli_query($link, $sql)) { // 打印结果 if (mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_array($result)) { echo $row['id'] . " " . $row['name'] . " " . $row['email']; echo "<br>"; } // 释放结果集资源 mysqli_free_result($result); } else { echo "No records found."; } } else { echo "Error: Could not able to execute $sql. " . mysqli_error($link); } // 关闭连接 mysqli_close($link); ?>
In the above code, we first use the mysqli_connect() function to connect to the MySQL database. We then query all the data in the users table, using the mysqli_query() function to execute the SQL statement and return the result set. Finally, we use the mysqli_fetch_array() function to obtain the query results row by row and output them to the page. Use the mysqli_free_result() function to release result set resources, and use the mysqli_close() function to close the connection.
- PHP PDO interacts with MySQL
PDO is a lightweight database abstraction layer of PHP that supports a variety of databases and provides simpler and more efficient database operations. Methods. Using PDO, we can use a single code base to operate multiple types of databases without changing the code. The following is a basic sample code, connect to the local MySQL database, query all data in the users table:
<?php // 连接 MySQL 数据库 $dsn = "mysql:host=localhost;dbname=database_name"; $username = "username"; $password = "password"; // 创建 PDO 实例 try { $pdo = new PDO($dsn, $username, $password); } catch (PDOException $e) { die("Error: Could not connect. " . $e->getMessage()); } // 查询 users 表中的所有数据 $sql = "SELECT * FROM users"; if ($result = $pdo->query($sql)) { // 打印结果 if ($result->rowCount() > 0) { while ($row = $result->fetch()) { echo $row['id'] . " " . $row['name'] . " " . $row['email']; echo "<br>"; } } else { echo "No records found."; } } else { echo "Error: Could not able to execute $sql. " . $pdo->errorInfo(); } // 关闭连接 $pdo = null; ?>
In the above code, we first create a PDO instance, using $dsn, $username and $password Connect to the MySQL database. We then query all the data in the users table, using the $pdo->query() function to execute the SQL statement and return the result set. Finally, we use the $result->fetch() function to fetch the query results row by row and output them to the page. Close the connection using the $pdo = null; statement.
- PHP ORM framework interacts with MySQL
ORM (Object Relational Mapping, object relational mapping) is a software framework used to establish mapping between objects and relational databases . The ORM framework is a high-level library that helps us develop and maintain applications more quickly. There are multiple ORM frameworks to choose from in PHP, including Laravel's Eloquent, Symfony's Doctrine, Yii2's ActiveRecord, etc. The following is a basic sample code that uses Eloquent ORM to connect to a local MySQL database and query all data in the users table:
<?php // 引入 Eloquent ORM 类 require_once "vendor/autoload.php"; use IlluminateDatabaseCapsuleManager as Capsule; // 创建 Eloquent ORM 实例 $capsule = new Capsule; // 配置数据库连接信息 $capsule->addConnection([ "driver" => "mysql", "host" => "localhost", "database" => "database_name", "username" => "username", "password" => "password", ]); // 启动 Eloquent ORM $capsule->bootEloquent(); // 查询 users 表中的所有数据 $users = Capsule::table("users")->get(); // 打印结果 if (count($users) > 0) { foreach ($users as $user) { echo $user->id . " " . $user->name . " " . $user->email; echo "<br>"; } } else { echo "No records found."; } ?>
In the above code, we first use Composer to install Eloquent ORM and introduce the corresponding classes . Then we create a Capsule instance and add database connection information. Start the Eloquent ORM using the $capsule->bootEloquent() function. Finally, we use the Capsule::table() function to query all the data in the users table and use a foreach loop to output it to the page row by row.
Conclusion
When operating databases in PHP, we have many choices. You can easily connect to the MySQL database using native MySQL functions, but the amount of code is relatively cumbersome. PDO can be used to connect to many types of databases and provides some efficient operation methods. Using an ORM framework can greatly simplify our code development and provide higher stability and maintainability. We need to choose the most appropriate method based on the specific needs of the project.
The above is the detailed content of How to operate database in PHP?. For more information, please follow other related articles on the PHP Chinese website!

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

PHP traits enable code reuse in single inheritance contexts, offering benefits like reusability and simplified inheritance. They can be effectively combined with traditional inheritance to enhance class flexibility and modularity.

PHP does not support multiple inheritance but uses interfaces and traits as alternatives to achieve similar functionality, avoiding issues like the diamond problem.

Inheritance in PHP allows classes to inherit properties and methods, promoting code reuse and hierarchical organization. Key benefits include reusability, abstraction, and polymorphism. Common mistakes to avoid are overuse of inheritance and ignoring

The article discusses three main error types in programming: syntax, runtime, and logical errors. It explains their causes, prevention strategies, impacts on performance and user experience, and methods for diagnosis and resolution.

Article discusses PHP and HTML interaction, best practices for embedding PHP in HTML, dynamic HTML content generation, and recommended development tools.

The article discusses the differences between for and foreach loops in PHP, focusing on syntax, usage, control, and performance. Foreach is preferred for array iteration due to simplicity and efficiency, but for loops are better for index-based opera

The article discusses the crucial role of the PHP parser in script execution, focusing on its tasks in syntax analysis, error handling, and code optimization, and how its efficiency impacts web application performance.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version

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