PHP database connection is completed in four steps: obtaining credentials, importing the MySQLi extension, creating the connection object, and closing the connection. For MySQL database, the connection example is as follows: require_once("mysqli.class.php"); $mysqli = new mysqli("localhost", "root", "password", "employees");
Beginner's Guide: Step by Step Establishing a PHP Database Connection
Establishing a database connection is an essential part of PHP development. This guide will walk you through setting up a PHP database connection step by step and provide a practical case for you to practice.
Step 1: Obtain database credentials
Obtain the following credentials from the database server administrator or service provider:
Step 2: Import the mysqli library
At the top of the script, import the MySQLi extension:
<?php require_once("mysqli.class.php"); // MySQLi 扩展的路径 ?>
Step 3: Create the connection object
Use mysqli::__construct()
Function creates a MySQLi connection object:
<?php $mysqli = new mysqli("主机名或 IP", "用户名", "密码", "数据库名"); ?>
Practical case: Connect to MySQL database
Assume we want to connect to a MySQL database named "employees", The host name is "localhost", the user name is "root", and the password is "password", the code is as follows:
<?php require_once("mysqli.class.php"); // MySQLi 扩展的路径 $mysqli = new mysqli("localhost", "root", "password", "employees"); ?>
If the connection is successful, the $mysqli object will contain the database connection.
Verify connection
You can check the $mysqli->connect_errno attribute to confirm whether the connection is successful. If it is 0, the connection is successful:
<?php if ($mysqli->connect_errno) { echo "连接失败: " . $mysqli->connect_error; } else { echo "连接成功"; } ?>
Close the connection
Use the mysqli_close()
function to close the connection and release resources:
<?php $mysqli->close(); ?>
The above is the detailed content of Beginner's Guide: Step-by-Step Setting Up a PHP Database Connection. For more information, please follow other related articles on the PHP Chinese website!