PHP代码段,用于连接MySQL数据库并查询数据

connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// SQL查询语句
$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"]. "
"; } } else { echo "0 结果"; } // 关闭连接 $conn->close(); ?>

这段代码首先设置了数据库的连接参数,然后创建了一个到MySQL数据库的连接。之后,它执行一个SQL查询来获取MyGuests表中的所有记录,并打印出每条记录的ID和姓名。最后,它关闭了数据库连接。请确保替换your_username, your_password, your_database为实际的数据库用户名、密码和数据库名。

首码库

你可能感兴趣的:(数据库,php,mysql)