How to Connect to a Database Using PHP
This tutorial explains how to connect PHP to databases using both mysqli and PDO, covering connection setup, error handling, executing queries, and properly closing the connection, with complete code examples for each method.
Using PHP to Connect to Database
Introduction
Connecting to a database in PHP is a fundamental task when developing web applications. This article will guide you step‑by‑step through the process required to connect PHP to various types of databases.
Establish Connection
To establish a database connection, you can use the following code:
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "成功连接到数据库";Using PDO
PDO (PHP Data Objects) is a more powerful connection method that provides a unified interface for different database types. There are three ways to create a PDO connection:
1. Object‑oriented style
$host = "localhost";
$port = "3306"; // MySQL default port
$dbname = "dbname";
$username = "username";
$password = "password";
$dsn = "mysql:dbname=$dbname;host=$host;charset=UTF8;port=$port";
try {
// Create connection
$conn = new PDO($dsn, $username, $password);
// Set error mode
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "成功连接到数据库";
} catch (PDOException $e) {
echo "连接失败: " . $e->getMessage();
}2. Using PDOStatement
$host = "localhost";
$database = "dbname";
$username = "username";
$password = "password";
// Create connection
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
// Prepare statement
$stmt = $conn->prepare("SELECT * FROM users");
$stmt->execute();
// Iterate results
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $result['id'] . ", 名称: " . $result['name'] . "
";
}3. Shortcut method
$dsn = "mysql:dbname=mydb;host=localhost";
$conn = new PDO($dsn, $username, $password);
// Practical example: retrieve user by userId
$userId = 1;
// Query statement
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId); // i indicates integer
$stmt->execute();
// Get result
$result = $stmt->get_result();
if ($row = $result->fetch_assoc()) {
echo "名称: " . $row['name'] . "
";
echo "电子邮件: " . $row['email'] . "
";
} else {
echo "没有找到用户";
}Close Connection
After completing database operations, be sure to close the connection to free resources:
$conn->close();php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.