Home  >  Article  >  Backend Development  >  How to connect to a remote MySQL database using PHP?

How to connect to a remote MySQL database using PHP?

WBOY
WBOYOriginal
2024-06-02 12:36:561077browse

How to connect to a remote MySQL database using PHP? Steps: Create PHP file. Use mysqli_connect() to establish a connection. Check if the connection is successful. Run the script to test the connection. Practical example: Execute a query to retrieve and print usernames.

如何使用 PHP 连接到远程 MySQL 数据库?

How to connect to a remote MySQL database using PHP

Prerequisites

  • PHP is installed.
  • The remote MySQL database has been created.
  • The connection details (hostname, username, password, port) of the remote MySQL database are known.

Step 1: Create a PHP file

Create a new PHP file, for example connect_to_remote_mysql.php.

Step 2: Establish a connection

In the PHP file, use the mysqli_connect() function to establish a connection to the remote MySQL database.

<?php
$hostname = 'remote_host_name';   // 远程数据库的主机名
$username = 'username';           // 数据库用户名
$password = 'password';           // 数据库密码
$database = 'database_name';       // 要连接的数据库名称
$port = 3306;                     // 数据库端口(通常为 3306)

$conn = mysqli_connect($hostname, $username, $password, $database, $port);

if (!$conn) {
    die("连接失败:" . mysqli_connect_error());
}
?>

Step 3: Check the connection

Check if the connection is successful by checking if the $conn variable is empty.

<?php
...
if (!$conn) {
    die("连接失败:" . mysqli_connect_error());
} else {
    echo "连接成功!";
}
...
?>

Step 4: Run the script to test the connection

Save the PHP file on your web server and access it through your browser. If you see the "Connection successful!" message, you have successfully connected to the remote MySQL database.

Practical case: Execute query

Using the established connection, you can execute the query, for example:

<?php
...
$query = "SELECT * FROM users";
$result = mysqli_query($conn, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "用户名:" . $row['username'] . "<br>";
    }
} else {
    echo "查询失败:" . mysqli_error($conn);
}
...
?>

This example queryusers table and print the username.

The above is the detailed content of How to connect to a remote MySQL database using PHP?. 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