我有一个在PDO中工作正常但我需要将查询转换为MySQLi以与旧服务器兼容的查询。
以下是PDO查询:
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username=:username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $username, PDO::PARAM_STR );
$st->execute();
while ( $row = $st->fetch() ) {
$db_username = $row['username'];
$db_password = $row['password'];
}
以下是我对MySQLi的看法,但它似乎并没有起作用:
$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );
$username = mysqli_real_escape_string($mysqli, $username);
$query = "SELECT * FROM users WHERE username=$username";
if ($result = $mysqli->query($query)) {
while ($obj = $result->fetch_object()) {
$db_username = $obj->username;
$db_password = $obj->password;
}
mysqli_free_result($result);
}
非常感谢任何帮助:)
答案 0 :(得分:1)
尝试使用mysqli预处理语句系统
$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );
$query = "SELECT username, password FROM users WHERE username=?";
$prep = $mysqli->prepare($query);
$prep->bind_param('s', $username);
$prep->execute();
$result = $prep->get_result(); // Make sure you have mysqlnd installed
if($result) {
while ($obj = $result->fetch_object()) {
$db_username = $obj->username;
$db_password = $obj->password;
}
mysqli_free_result($result);
}
如果您没有安装mysqlnd,那么不太直观的方法涉及bind_param
$prep->execute();
$prep->bind_result($db_username, $db_password);
$prep->fetch();