Introduction

Sometimes we need to use PHP to perform operations on a MySQL database. This article will explain how to use PHP to connect to a MySQL database.

Connecting to the Database

The following content can be directly written into the main PHP file or as a separate file.

1
2
3
4
5
6
7
8
9
10
11
12
$mysql_server_name = '127.0.0.1';
$mysql_username = 'root';
$mysql_password = '123456';
$mysql_database = 'sjk';
$conn = mysqli_connect($mysql_server_name, $mysql_username, $mysql_password, $mysql_database);
// Error message for database connection failure
if (mysqli_connect_errno($conn)) {
echo "<script>alert('Unable to connect to the database')</script>";
exit();
}
mysqli_query($conn, "set names utf8"); // Database encoding format
mysqli_set_charset($conn, "utf8"); // Set default client character set.

Executing SQL Statements

Query (write all contents from the database into the $data array).

1
2
3
4
5
6
$sql = "SELECT 姓名 FROM `G2022`";
$result = mysqli_query($conn, $sql);
$data = array();
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row);
}