dongqiangou5724 2018-02-11 09:31
浏览 118
已采纳

为什么mysqli_stmt_num_rows函数返回0?

I am trying to create a login page, but I'm having some issues using prepared statements to secure the login. I have the following code:

$sql = "SELECT * FROM users WHERE user_email=?";
$stmt = mysqli_stmt_prepare($db, $sql);
mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);

The problem occurs when checking if the result check variable is less than 1. It shouldn't be 0, but it is. I don't understand why, as the database has an email with the value test@test.com, but when trying to enter that the $resultCheck variable still returns 0. I'm guessing it has to do with the prepared statements.

  • 写回答

1条回答 默认 最新

  • dongying6896 2018-02-11 11:05
    关注

    The client has no idea how many rows are in the result until they are fetched.

    You can make the client pre-fetch all rows of the result by using mysqli_stmt_store_result(). Then you can use num-rows.

    $sql = "SELECT * FROM users WHERE user_email=?";
    $stmt = mysqli_prepare($db, $sql);
    mysqli_stmt_bind_param($stmt, "s", $email);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_store_result($stmt);
    $resultCheck = mysqli_stmt_num_rows($stmt);
    
    echo "result num_rows = $resultCheck
    ";
    

    This echo correctly produces the answer "1".

    But if you do use store-result, for some reason you can't also use get-result. So you can't use result methods like fetch_assoc — you have to bind_result into variables by reference and use fetch().

    By the way, mysqli_stmt_prepare() takes a statement object as its first argument, not the $db connection. Whereas mysqli_prepare() takes a connection object. Again, a confusing usage of mysqli functions.


    I don't like mysqli. It's hard to use and has confusing traps of inexplicable behavior. I don't like how bind_param and bind_result make my code seem cluttered.

    I prefer using PDO. It's much easier.

    $sql = "SELECT * FROM users WHERE user_email=?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$email]);
    $result = $stmt->fetchAll();
    $rowCount = $stmt->rowCount();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 ArcGIS Pro时空模式挖掘工具
  • ¥15 获取到海康hls的视频地址是http协议导致无法正常播放
  • ¥15 seL4如何实现从终端输入数据
  • ¥15 方波信号时频特征分析/信号调制与解调过程分析/利用DFT分析信号频谱
  • ¥20 两台硬件相同的琴设备一个是高阶版,怎么扒到初阶版
  • ¥30 matlab求解周期与坐标
  • ¥15 MATLAB图片转灰度格式问题
  • ¥15 把h5作品链接复制到自己的账号里
  • ¥15 ensp抓包实验配置
  • ¥15 强化学习算法、MRO
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部