阅读量:0
在PHP中,使用MySQLi函数连接和操作MySQL数据库时,需要正确设置参数。以下是一些常用的MySQLi函数及其参数设置:
mysqli_connect()
参数说明:
$host
:MySQL服务器的主机名或IP地址。$username
:用于连接到MySQL服务器的用户名。$password
:用于连接到MySQL服务器的密码。$database
:要连接的MySQL数据库名称(可选)。$port
:MySQL服务器的端口号(默认为3306)。
示例代码:
$conn = mysqli_connect("localhost", "username", "password", "database"); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } echo "连接成功";
mysqli_query()
参数说明:
$connection
:一个有效的MySQLi连接对象。$query
:要执行的SQL查询字符串。
示例代码:
$conn = mysqli_connect("localhost", "username", "password", "database"); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } $sql = "SELECT id, name 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"]. "<br>"; } } else { echo "0 结果"; } mysqli_close($conn);
mysqli_prepare()
参数说明:
$connection
:一个有效的MySQLi连接对象。$query
:要准备的SQL查询字符串。
示例代码:
$conn = mysqli_connect("localhost", "username", "password", "database"); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } $stmt = mysqli_prepare($conn, "INSERT INTO users (name, age) VALUES (?, ?)"); if (!$stmt) { die("准备查询失败: " . mysqli_error($conn)); } $name = "John"; $age = 25; mysqli_stmt_bind_param($stmt, "si", $name, $age); if (mysqli_stmt_execute($stmt)) { echo "新记录插入成功"; } else { echo "Error: " . mysqli_error($conn); } mysqli_stmt_close($stmt); mysqli_close($conn);
mysqli_real_escape_string()
参数说明:
$connection
:一个有效的MySQLi连接对象。$string
:要转义的字符串。
示例代码:
$conn = mysqli_connect("localhost", "username", "password", "database"); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } $username = "O'Reilly"; $password = "secret"; $username = mysqli_real_escape_string($conn, $username); $password = mysqli_real_escape_string($conn, $password); $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "登录成功"; } } else { echo "用户名或密码错误"; } mysqli_close($conn);
注意:在实际开发中,为了提高安全性,建议使用预处理语句(prepared statements)来防止SQL注入攻击。