0

在下面的代码中,我将功能从 MYSQL 升级到 MYSQLI,我在以前的帖子中得到了一些帮助,他们说应该做什么.. 但现在问题来了怎么做..

事情是在id之前设置,否则无论我登录哪个帐户return,我仍然会收到用户。ID = 1

function user_id_from_username($username) {
    $username = sanitize($username);
    global $db_connect;

    $result = $db_connect->query("SELECT(id) FROM members WHERE username = '$username'");
    if (false === $result) {
        return false;
    }
    return ($result->num_rows == 1) ? id : false;

我尝试按照旧MYSQL代码中的方式进行操作,但随后出现错误。我的旧代码:

    function user_id_from_username($username){
    $username = sanitize ($username);
    return mysql_result(mysql_query("SELECT(id) FROM members WHERE username = '$username'"), 0, 'id');
}

如果有任何帮助,我将不胜感激!

4

3 回答 3

0

你试过了吗fetch_arraymysqli_fetch_array

$row = $result->fetch_array(MYSQLI_ASSOC);
// or
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

// and returning
return $row['id'] ? $row['id'] : false;
于 2013-02-03T13:19:11.507 回答
0

我没有尝试过,但这应该可以正常工作吗?我还将 $db_connect 作为参数,因为它更安全,但取决于您。

function user_id_from_username($username) {
    $username = sanitize($username);
    global $db_connect;
    $result = $db_connect->query("SELECT id FROM members WHERE username = '".$db_connect->real_escape_string($username)."'");
    if (!$result) {
        return false;
    }
    if($result->num_rows == 1){
        $row = $result->fetch_assoc();
        $output = $row['id'];
    }
    else{
        $output = "Username does not exist in table or is a duplicate.";
    }
    return $output;
}
于 2013-02-03T13:37:26.193 回答
-2
return ($result->num_rows == 1) ? id : false;

应该

if(mysqli_num_rows($result) ===1 ){
    $row = mysqli_fetch_assoc($result);
    return intval($row['id']);
}
return false;
于 2013-02-03T13:21:54.730 回答