简体   繁体   English

使用数据库中的数据构建多维JSON字符串

[英]build multidimensional JSON string with data from database

Well.... 好....

I have a function where I need to retrieve data from my database (which contains info for google maps markers) and build a JSON string with that data.. Since I need a multidimensional json string, I thought this would be the best option for me. 我有一个函数,需要从数据库中检索数据(其中包含Google Maps标记的信息),并使用该数据构建JSON字符串。由于我需要多维JSON字符串,因此我认为这对我来说是最佳选择。

public function getAll(){
    $tables = ['huisartsenwachtposten', 'bioscopen'];
    $markers = [];

    for($i=0; $i<count($tables); $i++){
        $sql = "SELECT * FROM `:table`";

        $stmt = $this->db->prepare($sql);
        if ($stmt) {
            $stmt->bindParam(':table', str_replace("'", "", $tables[$i]));

            if ($stmt->execute()) {
                while($row = $stmt->fetch() ) {
                    $markers[$tables[$i]][] = $row;
                }
            }
        }   
    }
    return json_encode($markers);  
}

However, when I run this function. 但是,当我运行此功能时。 My browser shows me the following Error: "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'gepensioneerdgent.'huisartsenwachtposten'' doesn't exist" 我的浏览器向我显示以下错误:“ SQLSTATE [42S02]:找不到基表或视图:1146表'gepensioneerdgent.'huisartsenwachtposten”不存在”

Anyone that has a solution? 有解决方案的人吗? :) Thanks in advance :) 提前致谢

HS. HS。

ps I have more than the 2 tables used in this example... ps我不止有本示例中使用的2个表...

If you're using PDO, take a look at: http://php.net/manual/en/pdostatement.bindparam.php 如果您使用的是PDO,请查看: http : //php.net/manual/en/pdostatement.bindparam.php

bindParam() is just for columns, not for tables. bindParam()仅用于列,不适用于表。 You've to write down the tables names. 您必须写下表名称。

Try this (not tested!): 试试这个(未经测试!):

public function getAll(){
    $tables  = array('huisartsenwachtposten', 'bioscopen');
    $markers = array();

    for($i=0; $i<count($tables); $i++){
        $sql = "SELECT * FROM `".$tables[$i]."`";

        $stmt = $this->db->prepare($sql);
        if ($stmt) {
            if ($stmt->execute()) {
                while($row = $stmt->fetch() ) {
                    $markers[$tables[$i]][] = $row;
                }
            }
        }   
    }
    return json_encode($markers);  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM