要使用PHP操作MySQL数据库,您需要遵循以下步骤:
mysqli
或PDO
扩展。以下是使用这两种扩展的示例代码:使用mysqli
扩展:
$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);
}
使用PDO
扩展:
$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);
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
检索数据(SELECT):
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 结果";
}
插入数据(INSERT):
$sql = "INSERT INTO your_table (name, age) VALUES ('John Doe', 30)";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
更新数据(UPDATE):
$sql = "UPDATE your_table SET name='Jane Doe' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
删除数据(DELETE):
$sql = "DELETE FROM your_table WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "删除成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
使用mysqli
扩展关闭连接:
$conn->close();
使用PDO
扩展关闭连接:
$conn = null;
这就是使用PHP操作MySQL数据库的基本方法。请根据您的需求调整代码示例。