convert mysql result to json with correct types

后端 未结 4 446
南方客
南方客 2020-12-11 20:14

I know how to get a mysql-row and convert it to json:

$row = mysqli_fetch_assoc(mysqli_query($db, \"SELECT * FROM table WHERE id=1\"));
echo json_encode($row         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-11 20:47

    A MySQLi OO version based on @axiac's answer, that produces a JSON array ($jsnAll) containing all records. In this code snippet, the method FixSQLType is called to fix a row. Note, it should be wrapped in a try{}catch{} block and "objMySQLi" has already been instantiated:

             $lcAllRows = array();
    
             // Make an SQL SELECT statement 
             $SQL = "SELECT * FROM $lcName WHERE $lcWhere";
    
             // Run the query
             $this->sqlResult =  $this->objMySQLi->query($SQL);
    
             // Fetch the result
             while( $row = $this->sqlResult->fetch_assoc()){
                 $lcCount = count($lcAllRows) ;
    
                 // Call to fix, row 
                 $fixedRow = $this->FixSQLType($row);
                 $lcAllRows[$lcCount]= $fixedRow;
             }
    
             $jsnAll = json_encode($lcAllRows);
    

    The FixSQLType method. This is almost identical to @axiac's answer, except for the call to $this->sqlResult->fetch_field_direct($i). "fetch_field" seemed to get itself lost, using "fetch_field_direct" overcame that problem.

        private function FixSQLType($pRow){
        // FROM https://stackoverflow.com/a/28261996/7571029
    
        // Fix the types    
        $fixed = array();
        $i = 0;
        foreach ($pRow as $key => $value) {
            $info = $this->sqlResult->fetch_field_direct($i);
            $i++;
    
            if (in_array($info->type, array(
                    MYSQLI_TYPE_TINY, MYSQLI_TYPE_SHORT, MYSQLI_TYPE_INT24,    
                    MYSQLI_TYPE_LONG, MYSQLI_TYPE_LONGLONG,
                    MYSQLI_TYPE_DECIMAL, 
                    MYSQLI_TYPE_FLOAT, MYSQLI_TYPE_DOUBLE
            ))) {
                $fixed[$key] = 0 + $value;
            } else {
                $fixed[$key] = $value;
            }
    
        }
    
        return $fixed;
    }
    

提交回复
热议问题