-1

下面的 PHP 在插入的情况下可以正常工作,但是通过对绑定参数的选择查询,读取 json 并没有多少运气。我现在创建的应用程序总是在 if 语句评估行数时返回 false。我觉得问题确实在于 mysqli_stmt_store_result($query) 的范围。用户的登录凭据在尝试登录时不起作用,即使它们是正确的。如果需要更多信息,请告诉我。数据库连接没问题。

//parameter checking
$username = safe(stripslashes(trim($_POST['username'])));
$mypassword=hash('sha256', $salt.$_POST['password']);

//sanitize input parameters
function safe($value)
{
    global $db;

    $secureString = mysqli_real_escape_string($db, $value);

   return $secureString;
} 

//query check
$query= mysqli_prepare($db, "SELECT * FROM Users WHERE username =? AND password =? AND block_status < 1");
//$result=mysqli_query($db,$query);
mysqli_stmt_bind_param($query,'ss',$username,$mypassword);

mysqli_stmt_execute($query);

/* store result */
    mysqli_stmt_store_result($query);

$query2="UPDATE Users SET last_login=NOW() WHERE username ='" . $username . "' AND password = '" . $mypassword . "'";
$result2=mysqli_query($db,$query2);


//if match found, create an array of data and json_encode it
if(mysqli_stmt_num_rows($query)>0)
{


    $row=mysqli_fetch_array($query,MYSQLI_ASSOC);

    $response=array(

        'logged'=>true,
        'name'=>$row['name'],
        'email'=>$row['email']
    );

    echo json_encode($response);
}
else
{
    $response=array(

        'logged'=>false,
        'message'=>'Invalid credentials or your access has been revoked'
    );
    echo json_encode($response);
}

    /* free result */
    mysqli_stmt_free_result($query);

    /* close statement */
    mysqli_stmt_close($query);

    mysqli_close($db);

?>
4

1 回答 1

0

根据文档,您应该在调用mysql_stmt_store_result() 之前mysql_stmt_num_rows()使用。

此外,您应该为UPDATE查询使用参数绑定,但前提是您确认成功登录。

我强烈推荐 PDO 而不是 MySQLi。API 更简洁,更易于理解。这就是我将如何做到的......

// assuming your user table has a primary key `id`
$stmt = $db->prepare('SELECT `id`, `name`, `email` FROM `Users` WHERE `password` = ? AND `username` = ? AND block_status < 1');
$stmt->execute(array($passwordHash, $username));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user !== false) {
    $response = array('logged' => true) + $row;

    $update = $db->prepare('UPDATE `Users` SET `last_login` = NOW() WHERE `id` = ?');
    $update->execute(array($row['id']));
} else {
    $response = array(
        'logged'  => false,
        'message' => 'Invalid credentials or your access has been revoked'
    );
}

$stmt->closeCursor();

header('Content-type: application/json');
echo json_encode($response);
exit;
于 2013-07-19T04:11:24.820 回答