0

我在将其从 mysql 转换为 mysqli 时遇到问题,我尝试了 php 文档所说的内容,但我仍然无法得到它。任何帮助,将不胜感激。

return (mysql_result(mysql_query("SELECT COUNT(id) FROM users WHERE (username = '$username' OR email = '$username') AND password = '$password'"), 0) == 1) ? $user_id : false;

我试过这个:

return (mysqli_data_seek(mysqli_query($con,"SELECT COUNT(id) FROM users WHERE (username = '$username' OR email = '$username') AND password = '$password'"), 0) == 1) ? $user_id : false;

整体功能:

function login($username, $password){
$con=mysqli_connect("127.0.0.1","root","","frostbase");
    $user_id = user_id_from_username($username);


    $username = sanitize($username);
    $password = md5($password);

    return (mysqli_data_seek(mysqli_query($con,"SELECT COUNT(id) FROM users WHERE (username = '$username' OR email = '$username') AND password = '$password'"), 0) == 1) ? $user_id : false;
    mysqli_close($con);
}
4

1 回答 1

0

实际上,您可以做得更好。

safeMysql是一个工具,它可以帮助您将丑陋的旧的基于 mysql API 的代码转换为新的丑陋的基于 mysqli API 的代码,而是使用更好的方法。

关键是您不能在应用程序代码中使用原始 API 调用,mysql无论mysqliPDO. 但是将它们包装在一个库中,该库将执行所有必需的操作,如数据绑定、获取、错误处理、分析等等。

坦率地说,您只需编写查询 - 其余部分由 lib 完成:

$sql = "SELECT 1 FROM users WHERE (username = ?s OR email = ?s) AND password = ?s"; 
return (bool)$db->getOne($sql, $username, $username, $password); 

或者,以函数的形式

function login($username, $password){
    global $con; // you have to connect ONCE per application
    $sql = "SELECT 1 FROM users WHERE (username = ?s OR email = ?s) AND password = ?s"; 
    return (bool)$con->getOne($sql, $username, $username, $password); 
}
于 2013-06-19T08:20:04.437 回答