PHP准备语句结果数组未找到正确的值

时间:2013-07-19 03:45:43

标签: php mysql json mysqli prepared-statement

下面的PHP在插入实例中工作正常,但是对于绑定参数的选择查询,json读取没有太多运气。我现在创建的应用程序总是返回false,if语句评估行数。我觉得这个问题确实存在于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);

?>

1 个答案:

答案 0 :(得分:0)

根据docs,您应该在致电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;