PHP和MYSQLi - 使用循环和存储在数组中绑定参数?

时间:2009-07-05 23:00:24

标签: php content-management-system mysqli

下面是我用来从我的表中检索多个数据的函数的代码,但我想使用bind_result($ array [0],...,..)自动生成,具体取决于数量我在查询中选择的字段。

例如..

$query=select a,b,c,d,e from table;//selecting 5 fields
......
$stmt->execute();$stmt->bind_result($retrieve[0],$retrieve[1],$retrieve[2],$retrieve[3],$retrieve[4]);

(应自动生成5个值的bind_result) 将不胜感激帮助...谢谢你

$query="SELECT comment, userid,UNIX_TIMESTAMP(dtime)
                FROM comment_updates
                WHERE updateid=46546
                ORDER BY dtime DESC
                LIMIT 10 ";
        if($stmt = $this->conn->prepare($query)) {
            $stmt->execute();
            $stmt->bind_result($comments[0],$comments[1],$comments[2]);
            $i=0;
            while($stmt->fetch()){
            $i++;
            $name='t'.$i;
            $$name = array($comments[0],$comments[1],$comments[2]);
            }
            return array($i,$t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
            $stmt->close();
        }

1 个答案:

答案 0 :(得分:1)

这应该让你开始:

http://php.net/manual/en/mysqli-stmt.result-metadata.php

这将通过mysqli_num_fields()为您提供结果集中的字段数。

这应该是$retrieve数组的大小。

由于bind_result不将数组作为参数,因此您需要使用call_user_func_array来实现此目的:

call_user_func_array(array($stmt, 'bind_result'), $retrieve_references);

$retrieve_references应该是对$retrieve中元素的引用数组。在$retrieve中使用call_user_func_array本身会触发错误。