Home Backend Development PHP Tutorial How to operate database in PHP?

How to operate database in PHP?

May 21, 2023 am 08:30 AM
php – php is a popular programming language Widely used in web development and server-side programming. Database - A database is a collection of related data Can be organized, managed and accessed. Operations - Operations refer to operations such as creating, reading, updating, and deleting data in the database to achieve a specific purpose.

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.

  1. 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);
?>
Copy after login

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.

  1. 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;
?>
Copy after login

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.

  1. 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.";
}
?>
Copy after login

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!

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

Video Face Swap

Video Face Swap

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

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)

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

See all articles