要使用PHP操作MySQL数据库,您需要遵循以下步骤:
使用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();
}
插入数据:
$sql = "INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2')";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
查询数据:
$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["column1"]. " - Value: " . $row["column2"]. "<br>";
}
} else {
echo "0 结果";
}
更新数据:
$sql = "UPDATE your_table SET column1 = 'new_value1' WHERE id = 1";
if ($conn->query($sql) === TRUE) {
echo "更新成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
删除数据:
$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数据库的基本方法。请根据您的具体需求调整代码。