PHP是一种广泛使用的服务器端脚本语言,特别适用于Web开发。MySQL是一种流行的关系型数据库管理系统(RDBMS),用于存储和管理数据。PHP连接MySQL是指通过PHP脚本与MySQL数据库进行交互,执行查询、插入、更新和删除等操作。
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "连接成功";
// 执行查询
$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();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "连接成功";
// 执行查询
$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元无门槛券
手把手带您无忧上云