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.

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失