douyingzhan5905 2013-08-28 21:42
浏览 31
已采纳

sql准备语句获取结果到php变量[关闭]

What i want is to write this code with prepared statement:

if (mysqli_num_rows(mysqli_query($link,"select name from accounts where name='$username'"))==1)
        {
            // some actions
        }

Well, how to do that?

I know how to make a prepared "INSERT INTO" statement because I don't need to get the mysqli_query result into a php variable, but how to save a "SELECT" prepare statement to run mysqli_num_rows($result) right after?

EDIT: What I want to do is to execute a mysqli_query() with prepared statements while saving the result into a php $result variable. how to do that?

  • 写回答

1条回答 默认 最新

  • dongshuo9350 2013-08-28 21:49
    关注

    should never EVER chain database operations like that. You are assuming that the query will always succeed. This is BAD practice. Never assume success. Always assume the operations will fail, and treat success as a pleasant surprise.

    Since you're daisy-chaining the DB calls like that, you never actually capture the result handle that mysqli_query() will return, so in effect you're running the query and then throwing away its results.

    You should have something more like

    $result = mysqli_query($link, "....") or die(mysqli_error());
    if (mysqli_num_rows($result)) == 1) {
        $row = mysqli_fetch_assoc($result);
        $anem = $row['name'];
    }
    

    And unless you've taken steps not shown in this code, you are vulnerable to SQL injection attacks.

    As for the prepared statement stuff:

    $stmt = mysqli_prepare($link, 'SELECT ... WHERE name=?');
    mysqli_stmt_bind_param($stmt, 's', $name);
    mysqli_stmt_execute($stmt);
    
    $rows = mysqli_stmt_num_rows($stmt);
    
    mysqli_stmt_bind_result($stmt, $fetched_name);
    
    mysqli_stmt_fetch($stmt); // $fetched_name now contains the name from the DB
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?