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.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀