在PHP中实现与MySQL数据库的连接可以使用以下步骤:
使用mysqli扩展连接MySQL数据库的示例代码如下:
$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 "连接成功";
使用PDO扩展连接MySQL数据库的示例代码如下:
$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 "连接成功";
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
使用mysqli扩展执行查询语句的示例代码如下:
$sql = "SELECT * FROM table_name";
$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 结果";
}
$conn->close();
使用PDO扩展执行查询语句的示例代码如下:
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
if ($stmt->rowCount() > 0) {
// 输出数据
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 结果";
}
$conn = null;
以上是实现在PHP中与MySQL数据库连接的基本步骤,您可以根据具体需求进一步扩展和优化代码。