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 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系