简体   繁体   中英

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.

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"

Anyone that has a solution? :) Thanks in advance

HS.

ps I have more than the 2 tables used in this example...

If you're using PDO, take a look at: http://php.net/manual/en/pdostatement.bindparam.php

bindParam() is just for columns, not for tables. 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);  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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