How to connect to database using PHP built-in functions?

WBOY
Release: 2024-04-23 08:06:02
Original
371 people have browsed it

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.

如何使用 PHP 内置函数连接到数据库?

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

  • PHP is installed on your system.
  • MySQL database has been created and configured.

Steps

  1. Load MySQL extension

    Useextension=mysqli directive loads the MySQL extension into your php.ini configuration file.

  2. 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);
    Copy after login
    • $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)
  3. 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();
    }
    Copy after login

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();
}
Copy after login

Close the connection

Use the mysqli_close() function to close the connection.

mysqli_close($mysqli);
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template