doujuxin7392 2012-07-26 04:33
浏览 46
已采纳

如何使stmt_fetch将结果转换为mysqli中的数组

I am getting so frustrated with this. I am trying to make an array containing the values of a column using mysqli. Right now when i echo what is returned it is printing nothing. I have tried so many things i can not figure this out.

<?php 
class Database {

    public $dbHost = '';
    public $dbUser = '';
    public $dbPass = '';
    public $dbName = '';

    public $db;

    public function __construct(){ 
        $this->dbConnect();
    }

    public function dbConnect(){

        $this->db = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);

        /* check connection */
        if (mysqli_connect_errno()){
            printf("Connect failed: %s
", mysqli_connect_error());
            exit();
        }else{
            echo 'connection made';
        }
    }

    public function q($sql){
        $query = $sql;
        self::preparedStatement($query);
    }

    public function preparedStatement($query){
        $i= 0; //index
        $result = array();

        if ($stmt = $this->db->prepare($query)){ 

            /* execute statement */
            if($stmt->execute()) {
                $stmt->bind_result($name);
                while($stmt->fetch()) {
                    $result[0] = $name;
                }
            } else
                echo "error";

            /* close statement */
            $stmt->close();
        } else {
            echo "Prepare failed: (" . $stmt->errno . ") " . $stmt->error;
        }

        return $result;
    }

    public function __destruct(){}

}


### Test code

$db = new Database();
$res = $db->q("SELECT name FROM test");
echo $res[0];

?>
  • 写回答

1条回答 默认 最新

  • duanqia9034 2012-07-26 04:43
    关注

    first of all, remove the 0 in your while loop. You want the values to be stored in an array one after the other, what you're doing is always overwriting the first value in the array, and you need to store the value you get from fetch() in a temporary array.

    while($row = $stmt->fetch(MYSQLI_ASSOC)) {
       $result[] = $row['name'];
    }
    

    second, you need your q() function to return some value, so change the last statement to

    return self::preparedStatement($query);
    

    Please spend some time Googling about this and looking at examples of how other people are doing it.

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

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名