使用PHP连接数据库的代码可以按照以下步骤编写:
mysqli_connect()
函数连接到数据库。该函数需要提供数据库服务器的主机名、用户名、密码和数据库名称作为参数。示例代码如下:$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
mysqli_query()
函数来执行查询,并使用mysqli_fetch_assoc()
函数来获取结果集中的数据。示例代码如下:$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "
";
}
} else {
echo "0 结果";
}
mysqli_close()
函数来关闭连接。示例代码如下:mysqli_close($conn);
综合起来,完整的PHP连接数据库的代码如下所示:
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
$sql = "SELECT id, name, email FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "
";
}
} else {
echo "0 结果";
}
mysqli_close($conn);
以上代码演示了连接到数据库、执行查询并输出结果的过程。根据实际需求,你可以根据需要执行其他操作,如插入、更新或删除数据。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: php调用函数的方法有哪些