PHP 连接 MySQL 数据库需七步:建立连接(msiql_connect())准备查询(mysqli_prepare())绑定参数(mysqli_stmt_bind_param())执行查询(mysqli_stmt_execute())获取结果(mysqli_stmt_get_result())遍历结果(mysqli_fetch_assoc())关闭连接(mysqli_close())
PHP 数据库连接所需的步骤,从基础到进阶
1. 基础连接
使用 mysqli_connect() 函数建立与 MySQL 数据库的连接:
$mysqli = mysqli_connect("localhost", "username", "password", "database"); if (!$mysqli) { echo "Unable to connect to the database: " . mysqli_connect_error(); exit(); }
2. 准备查询
使用 mysqli_prepare() 函数准备一个查询:
$stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
3. 绑定参数
使用 mysqli_stmt_bind_param() 函数绑定查询中的参数:
$param = 3; mysqli_stmt_bind_param($stmt, "i", $param);
4. 执行查询
使用 mysqli_stmt_execute() 函数执行查询:
mysqli_stmt_execute($stmt);
5. 获取结果
使用 mysqli_stmt_get_result() 函数获取查询结果:
$result = mysqli_stmt_get_result($stmt);
6. 遍历结果
使用 mysqli_fetch_assoc() 函数遍历查询结果:
while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row['id'] . "<br>"; echo "Name: " . $row['name'] . "<br>"; }
7. 关闭连接
使用 mysqli_close() 函数关闭与数据库的连接:
mysqli_close($mysqli);
实战案例
连接到数据库并查询用户
$mysqli = mysqli_connect("localhost", "username", "password", "database"); if (!$mysqli) { echo "Unable to connect to the database: " . mysqli_connect_error(); exit(); } $stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?"); mysqli_stmt_bind_param($stmt, "i", $param); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); while ($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row['id'] . "<br>"; echo "Name: " . $row['name'] . "<br>"; } mysqli_close($mysqli);
以上是PHP数据库连接所需的步骤,从基础到进阶的详细内容。更多信息请关注PHP中文网其他相关文章!