MySQLI准备语句:num_rows& fetch_assoc [英] MySQLI Prepared Statement: num_rows & fetch_assoc

查看:88
本文介绍了MySQLI准备语句:num_rows& fetch_assoc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一些编写得很差并且被误解严重的PHP代码,没有进行错误检查.老实说,我在努力迷惑PHP-> MySQLi函数的迷宫!有人可以举一个例子,说明如何使用准备好的语句在关联数组中收集结果,同时又从$ stmt获取行数吗?下面的代码是我正在玩的东西.我认为让我失望的是在store_result之后使用$stmt值,然后尝试收集一个assoc数组,但我不太确定为什么...

Below is some poorly written and heavily misunderstood PHP code with no error checking. To be honest, I'm struggling a little getting my head around the maze of PHP->MySQLi functions! Could someone please provide an example of how one would use prepared statements to collect results in an associative array whilst also getting a row count from $stmt? The code below is what I'm playing around with. I think the bit that's throwing me off is using $stmt values after store_result and then trying to collect an assoc array, and I'm not too sure why...

$mysqli = mysqli_connect($config['host'], $config['user'], $config['pass'], $config['db']);
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
$stmt->bind_param('i', $core['id']);
$result = $stmt->execute();
$stmt->store_result();

if ($stmt->num_rows >= "1") {

    while($data = $result->fetch_assoc()){ 
        //Loop through results here $data[] 
    }

}else{

    echo "0 records found";

}

我只是想索要代码而感到有些厚脸皮,但这是对我的处境的有效演示,我觉得我需要最终了解实际发生的情况.谢谢一百万!

I feel a little cheeky just asking for code, but its a working demonstration of my circumstances that I feel I need to finally understand what's actually going on. Thanks a million!

推荐答案

是的,数据库功能有点奇怪.您会到达那里.

True, the Databasefunctions are a bit weird. You'll get there.

代码看起来有些杂乱无章,但这是它的工作原理:

The code looks a bit iffy, but heres how it works:

建立连接,准备语句,绑定参数并执行连接都很好.

A connection is build, a statement prepared, a parameter bound and it's executed, all well.

$result = $stmt->execute(); //execute() tries to fetch a result set. Returns true on succes, false on failure.
$stmt->store_result(); //store_result() "binds" the last given answer to the statement-object for... reasons. Now we can use it!

if ($stmt->num_rows >= "1") { //Uses the stored result and counts the rows.

  while($data = $result->fetch_assoc()){ 
        //And here, the answer-object is turned into an array-(object)
        // which can be worked with nicely.
        //It loops trough all entries in the array.
  }

}else{

   echo "0 records found";
}

这篇关于MySQLI准备语句:num_rows& fetch_assoc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆