准备好的声明程序

时间:2015-03-08 20:57:33

标签: php mysql prepared-statement

我需要将以下内容转换为程序性准备语句。我很难有这个。我能够为注册做到这一点,但不能用于登录。请帮助我使用程序准备声明转换以下内容。

if (empty($errors)) {
    $q = "SELECT first_name, user_id FROM users WHERE email='$e' AND pass=SHA1('$p')";
    $r = @mysqli_query ($dbc, $q);
    if (mysqli_num_rows($r) == 1) {
        $row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
        return array(true, $row);
    } else { //If credentials are incorrect
        $errors[] = 'The email or password is incorrect. Please try again';
    }
} // End of Empty Errors

1 个答案:

答案 0 :(得分:1)

我不确定你在问什么。但是,如果您想更改代码以使用prepared statement,则应该可以使用:

// connect to server 
$con = new mysqli('<hostname>','<username>','<password>','<database>');
if(empty($errors)) {
  // create a prepared statement
  $stmt = $con->prepare("SELECT first_name, user_id FROM users 
                         WHERE email = ? && pass=SHA1(?)");
  // bind parameters
  $stmt->bind_param('ss', $e, $p);
  // bind result
  $first_name = '';
  $user_id = 0;
  $stmt->bind_result($first_name, $user_id);
  // execute the query
  $stmt->execute();
  // store result so we can call `$num_rows` immediately
  $stmt->store_result();
  if($stmt->num_rows == 1) {
     // fetch the data
     $stmt->fetch();
     return array(true, array($user_id, $first_name));
  } else {
     errors[] = 'The email or password is incorrect. Please try again';
  }
}