PHP连接MySQL服务器是指使用PHP脚本语言与MySQL数据库进行交互的过程。通过这种连接,PHP应用程序可以执行SQL查询、插入、更新和删除数据等操作。
PHP连接MySQL广泛应用于各种Web应用程序,如博客、电子商务网站、社交媒体平台等。
mysqli
或PDO
扩展来连接MySQL服务器。mysqli
扩展<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
// 执行SQL查询
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 结果";
}
$conn->close();
?>
PDO
扩展<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "连接成功";
// 执行SQL查询
$stmt = $conn->query("SELECT id, firstname, lastname FROM MyGuests");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
$conn = null;
?>
通过以上步骤和示例代码,你应该能够成功配置PHP连接MySQL服务器。如果遇到具体问题,可以根据错误信息进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云