使用mysqli或PDO扩展函数连接MySQL数据库,执行SQL查询语句获取数据。
要连接MySQL数据库并获取数据,可以使用PHP的mysqli扩展或PDO扩展,下面是一个使用mysqli扩展的示例:
1、创建数据库连接
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn>connect_error) { die("连接失败: " . $conn>connect_error); } ?>
2、编写SQL查询语句
$sql = "SELECT id, firstname, lastname FROM MyGuests";
3、执行查询并获取结果
$result = $conn>query($sql);
4、输出查询结果
if ($result>num_rows > 0) { // 输出每行数据 while($row = $result>fetch_assoc()) { echo "id: " . $row["id"]. " Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 结果"; }
5、关闭数据库连接
$conn>close(); ?>
完整代码如下:
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn>connect_error) { die("连接失败: " . $conn>connect_error); } $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(); ?>
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/487890.html