dongtang1997
2015-08-25 09:29
浏览 67
已采纳

准备好的语句和mysqli_query / mysqli_num_rows?

I am trying to find out how to make my code work with prepared statements. I understood the entire process up to where I commented my code. What do I have to do in order to integrate num_rows and the mysqli_query part properly?

function login_check() {

    global $connection;

    $name = $_POST['name'];
    $password = $_POST['password'];

    $query = "SELECT id FROM members WHERE name = $name AND password = $password";
    $stmt = $connection->prepare($query);
    $stmt->bind_param('ss', $name, $password); 
    $stmt->execute();
    $stmt->close();

    // $result = mysqli_query($connection, $query);
    // $rows = mysqli_num_rows($result);

    if($rows > 0){
        header('location:../../success.php');
        exit;
    }

    else {
        header('location:../../failed.php');
        exit;
    }
}

What I tried:

$result = mysqli_query($connection, $stmt);
$rows = mysqli_num_rows($result);
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dttvb115151 2015-08-25 09:34
    已采纳

    Change

    $query = "SELECT id FROM members WHERE name = $name AND password = $password";
    

    to

    $query = "SELECT `id` FROM `members` WHERE `name` = ? AND `password` = ?";
    

    Adding backticks around table and columns prevents mysql reserved words error.

    Remove $stmt->close();

    if( $stmt->num_rows > 0 ) {
        $stmt->close();
        header('location:../../success.php');
        exit();
    } else {
        $stmt->close();
        header('location:../../failed.php');
        exit();
    }
    

    Adding $stmt->close() inside if statement before header is best practice in this case. Becasue adding it before if statement would result in $stmt->num_rows always returning 0; Adding it after the if statment won't work because exit() would prefent it from executing.

    From the documentation:

    Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题