Home  >  Article  >  Backend Development  >  How to realize php and mysql database connection

How to realize php and mysql database connection

PHPz
PHPzOriginal
2023-03-29 11:34:412179browse

PHP is an open source server-side programming language that is widely used in web development and works closely with the MySQL database. PHP and MySQL work together to provide developers with a powerful and efficient web development platform. This article will lead readers to understand how to realize the connection between PHP and MySQL databases, so that you can more flexibly use these two powerful tools to develop web applications.

1. Install and configure the MySQL database

Before starting the connection between MySQL and PHP, you need to install and configure the MySQL database first. If you have not installed MySQL, you can download the MySQL installation package from the official website and install it according to the instructions. During the installation process, remember to add the MySQL bin directory to the environment variables, which will help with subsequent configuration and connection operations. After the installation is complete, you will need to set up and configure MySQL, such as creating users, granting permissions to users, etc.

2. Prepare the PHP environment

Before connecting to MySQL, you also need to prepare the PHP environment. If you are using a Web integrated development environment such as WAMP or XAMPP, then the PHP environment is already ready. If you set up the PHP environment manually, you need to ensure that the PHP version meets the requirements and that the relevant PHP modules have been installed. MySQL has an official PHP extension mysqlnd, which provides better MySQL support and better performance. Additionally, there is a mysqli extension that provides more functionality and better error handling.

3. Use mysqli to connect to MySQL

Once you have prepared MySQL and PHP and ensure that the PHP extension is installed, you can start writing PHP code to connect to MySQL. The following is an example of using mysqli to connect to MySQL:

<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "dbname";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检测连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
?>

In this example, we first define the MySQL server address (localhost), user name, password and database name. Then I created a connection object using the mysqli class and passed these parameters. To ensure the connection is successful, we also add a connect_error check. Finally, confirm that the connection has been successfully established by outputting a message on the PHP page.

4. Use PDO to connect to MySQL

In addition to the mysqli extension, PHP also provides another standard way to connect to MySQL - PDO (PHP database object). PDO provides richer functions and safer data processing.

The following is an example of using PDO to connect to MySQL:

<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // 设置 PDO 错误模式为异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "连接成功"; 
}
catch(PDOException $e)
{
    echo "连接失败: " . $e->getMessage();
}
?>

In this example, we also define the address, user name, password and database name of the MySQL server. Then I created a connection object using PDO and passed these parameters. To ensure a successful connection, we also added an exception handler to prevent connection problems from causing the program to crash.

5. Connect to MySQL and perform query operations

Once you have established a connection to MySQL, you can perform various query operations through PHP. For query statements, you can use the query() method provided by mysqli or PDO to query. For example, the following is a simple example of executing a SELECT statement through mysqli:

<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

$sql = "SELECT * FROM orders";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // 输出数据
    while($row = $result->fetch_assoc()) {
        echo "订单号:" . $row["order_id"]. " - 客户名:" . $row["customer_name"]. " - 总价:" . $row["order_total"]. "<br>";
    }
} else {
    echo "0 结果";
}
$conn->close();
?>

In this example, we executed a SELECT statement, selected all the data from the data table orders, and traversed it through a while loop Output this data. If the query result is empty, "0 results" will be output, otherwise the query result will be output.

Summary

PHP and MySQL are a powerful combination. The connection between them is usually used to process data in web applications, allowing developers to create powerful and flexible web applications. . By introducing examples of connecting to MySQL through mysqli and PDO, this article hopes to provide some guidance for novice readers and help developers better utilize these tools to implement the design and development of Web applications.

The above is the detailed content of How to realize php and mysql database connection. 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