This article describes the steps to connect to a MySQL database using PHP's built-in mysqli_* functions: Load the MySQL extension. To establish a connection, a hostname, username, password, database name and port are required. Check if the connection is successful. Practical case: Connect to the database named "test_db", the user name is "root", the password is empty, and the host name is "localhost". Close the connection.
Connect to the database using PHP built-in functions
PHP provides a variety of built-in functions to connect to different types of databases. This article will demonstrate how to use the mysqli_*
function to connect to a MySQL database.
Prerequisites
Steps
Load MySQL extension
Useextension=mysqli
directive loads the MySQL extension into your php.ini configuration file.
Establish a connection
Call the mysqli_connect()
function to establish a connection to the database. This function requires five parameters:
$mysqli = mysqli_connect($host, $username, $password, $database, $port);
$host
: The host name or IP address of the database server $username
: Use User name used to connect to the database$password
: Password used to connect to the database$database
: Name of the database to be connected$port
: The port the database server listens on (default is 3306) Check the connection
Use the mysqli_connect_errno()
and mysqli_connect_error()
functions to check whether the connection is successful.
if (mysqli_connect_errno()) { echo "连接失败: " . mysqli_connect_error(); }
Practical case
Connect to a database named "test_db", the user name is "root", the password is empty, the host Named "localhost".
$mysqli = mysqli_connect("localhost", "root", "", "test_db"); if (mysqli_connect_errno()) { echo "连接失败: " . mysqli_connect_error(); }
Close the connection
Use the mysqli_close()
function to close the connection.
mysqli_close($mysqli);
The above is the detailed content of How to connect to database using PHP built-in functions?. For more information, please follow other related articles on the PHP Chinese website!