PHP原生连接MySQL可以通过使用mysqli或PDO扩展来实现。
使用mysqli扩展连接MySQL的示例代码如下:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 执行SQL查询或操作
$sql = "SELECT * FROM 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 结果";
}
// 关闭连接
$conn->close();
?>
使用PDO扩展连接MySQL的示例代码如下:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "连接成功";
// 执行SQL查询或操作
$sql = "SELECT * FROM table";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 关闭连接
$conn = null;
?>
请根据实际情况将上述代码中的$servername
、$username
、$password
和$dbname
替换为您的MySQL服务器的相关信息。
上一篇:PHP+MySQL消息队列
下一篇:PHP访问MySQL查询超时设置
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站