PHP Database Query Examples
In PHP, you can use the MySQLi or PDO extensions to connect to a database and execute queries. Below is an example code demonstrating how to connect to a database and retrieve query results:
Utilize the MySQLi extension:
// 连接数据库
$connection = new mysqli('localhost', 'username', 'password', 'database_name');
// 检查连接是否成功
if ($connection->connect_error) {
die('数据库连接失败: ' . $connection->connect_error);
}
// 执行查询
$query = $connection->query('SELECT * FROM table_name');
// 检查查询是否成功
if ($query) {
// 获取查询结果
while ($row = $query->fetch_assoc()) {
// 处理查询结果
echo $row['column_name'] . '<br>';
}
} else {
echo '查询失败: ' . $connection->error;
}
// 关闭数据库连接
$connection->close();
Utilize the PDO extension:
// 连接数据库
$dsn = 'mysql:host=localhost;dbname=database_name';
$username = 'username';
$password = 'password';
try {
$connection = new PDO($dsn, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die('数据库连接失败: ' . $e->getMessage());
}
// 执行查询
$query = $connection->query('SELECT * FROM table_name');
// 获取查询结果
while ($row = $query->fetch()) {
// 处理查询结果
echo $row['column_name'] . '<br>';
}
// 关闭数据库连接
$connection = null;
By using the code examples above, you can successfully connect to a database and retrieve query results. In practical applications, it is necessary to modify and expand the code according to specific requirements and database operations.