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

准备好的语句和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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型