【问题标题】:JSON encode MySQL resultsJSON 编码 MySQL 结果
【发布时间】:2010-09-27 20:55:26
【问题描述】:

如何在 MySQL 查询结果中使用 json_encode() 函数?我需要遍历行还是可以将其应用于整个结果对象?

【问题讨论】:

  • 我知道这是一个非常古老的问题。但是没有人展示解决整数显示为字符串的问题的最简单替代方法。 @mouckatron 在下面的答案中提供了 json_encode() 的 JSON_NUMERIC_CHECK 标志。简单,它就像一个魅力! stackoverflow.com/questions/1390983/…
  • 有一个关于字符串类型问题的匹配问题+答案:stackoverflow.com/questions/28261613/…

标签: php mysql json


【解决方案1】:
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

函数 json_encode 需要 PHP >= 5.2 和 php-json 包 - 如提到的 here

注意mysql 自 PHP 5.5.0 起已弃用,请使用 mysqli 扩展名代替 http://php.net/manual/en/migration55.deprecated.php

【讨论】:

  • 我建议您在选择查询期间使用AS 将列重命名为公共名称,例如SELECT blog_title as title,这样更干净,公众不知道什么确切的列来自数据库。
  • 此代码错误地将所有数值编码为字符串。例如,名为 score 的 mySQL 数字字段的 JSON 值将是“12”而不是 12(注意引号)。
  • @RobertPitt,基于隐藏列名称的安全性是security by obscurity
  • @Tomas 是的,但是知道确切的列名会使 SQL 注入攻击变得容易得多
  • @Tim:如果您的列名已知是 SQL 注入的唯一障碍,那么您已经失去了,不是吗?
【解决方案2】:

试试这个,这将正确地创建你的对象

 $result = mysql_query("SELECT ...");
 $rows = array();
   while($r = mysql_fetch_assoc($result)) {
     $rows['object_name'][] = $r;
   }

 print json_encode($rows);

【讨论】:

  • +1 这似乎是唯一提供与json.org/example 示例格式相同的 JSON 的答案。
  • 是的,这个例子给出了每行一个键。
【解决方案3】:

http://www.php.net/mysql_query 说“mysql_query() 返回一个资源”。

http://www.php.net/json_encode 表示它可以对“资源除外”的任何值进行编码。

您需要遍历并将数据库结果收集到一个数组中,然后json_encode 数组。

【讨论】:

  • mysql_query 不返回结果集。这就是 mysql_fetch* 的用途。
  • 嗯...是的...这就是 mysql_query 和 json_encode 之间的迭代。好电话,华生。
【解决方案4】:

谢谢..我的回答是:

if ($result->num_rows > 0) {
            # code...
            $arr = [];
            $inc = 0;
            while ($row = $result->fetch_assoc()) {
                # code...
                $jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
                $arr[$inc] = $jsonArrayObject;
                $inc++;
            }
            $json_array = json_encode($arr);
            echo $json_array;
        }
        else{
            echo "0 results";
        }

【讨论】:

    【解决方案5】:

    下面的代码在这里可以正常工作!

    <?php
    
      $con=mysqli_connect("localhost",$username,$password,databaseName);
    
      // Check connection
      if (mysqli_connect_errno())
      {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    
      $query = "the query here";
    
      $result = mysqli_query($con,$query);
    
      $rows = array();
      while($r = mysqli_fetch_array($result)) {
        $rows[] = $r;
      }
      echo json_encode($rows);
    
      mysqli_close($con);
    ?>
    

    【讨论】:

      【解决方案6】:

      根据我的经验,在您命名根元素之前,上述方法不起作用 在数组中的东西,我一直无法访问任何东西 在此之前的最终 json。

      $sth = mysql_query("SELECT ...");
      $rows = array();
      while($r = mysql_fetch_assoc($sth)) {
          $rows['root_name'] = $r;
      }
      print json_encode($rows);
      

      这应该可以解决问题!

      【讨论】:

        【解决方案7】:

        使用 PDO 时

        使用fetchAll() 获取所有行作为关联数组。

        $stmt = $pdo->query('SELECT * FROM article');
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($rows);
        

        当你的 SQL 有参数时:

        $stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
        $stmt->execute([1]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($rows);
        

        当您需要重新设置表的密钥时,您可以使用foreach 循环并手动构建数组。

        $stmt = $pdo->prepare('SELECT * FROM article WHERE id=?');
        $stmt->execute([1]);
        
        $rows = [];
        foreach ($stmt as $row) {
            $rows[] = [
                'newID' => $row['id'],
                'Description' => $row['text'],
            ];
        }
        
        echo json_encode($rows);
        

        使用mysqli时

        使用fetch_all() 获取所有行作为关联数组。

        $res = $mysqli->query('SELECT * FROM article');
        $rows = $res->fetch_all(MYSQLI_ASSOC);
        echo json_encode($rows);
        

        当您的 SQL 有参数时,您需要执行 prepare/bind/execute/get_result。

        $id = 1;
        $stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
        $stmt->bind_param('s', $id); // binding by reference. Only use variables, not literals
        $stmt->execute();
        $res = $stmt->get_result(); // returns mysqli_result same as mysqli::query()
        $rows = $res->fetch_all(MYSQLI_ASSOC);
        echo json_encode($rows);
        

        当您需要重新设置表的密钥时,您可以使用foreach 循环并手动构建数组。

        $stmt = $mysqli->prepare('SELECT * FROM article WHERE id=?');
        $stmt->bind_param('s', $id);
        $stmt->execute();
        $res = $stmt->get_result();
        
        $rows = [];
        foreach ($res as $row) {
            $rows[] = [
                'newID' => $row['id'],
                'Description' => $row['text'],
            ];
        }
        
        echo json_encode($rows);
        

        使用 mysql_* API 时

        请尽快升级到受支持的 PHP 版本!请认真对待。如果您需要使用旧 API 的解决方案,可以这样做:

        $res = mysql_query("SELECT * FROM article");
        
        $rows = [];
        while ($row = mysql_fetch_assoc($res)) {
            $rows[] = $row;
        }
        
        echo json_encode($rows);
        

        【讨论】:

        • 我原以为重新键入结果的示例使用列别名会更好,因为这消除了对循环的需要。
        【解决方案8】:

        我的简单修复方法是阻止它在数值周围放置语音标记...

        while($r = mysql_fetch_assoc($rs)){
            while($elm=each($r))
            {
                if(is_numeric($r[$elm["key"]])){
                            $r[$elm["key"]]=intval($r[$elm["key"]]);
                }
            }
            $rows[] = $r;
        }   
        

        【讨论】:

        • 用户 JSON_NUMERIC_CHECK 标志而不是 json_encode(getHistory($query), JSON_NUMERIC_CHECK );
        【解决方案9】:

        抱歉,这个问题问得太久了,但是:

        $sql = 'SELECT CONCAT("[", GROUP_CONCAT(CONCAT("{username:'",username,"'"), CONCAT(",email:'",email),"'}")), "]") 
        AS json 
        FROM users;'
        $msl = mysql_query($sql)
        print($msl["json"]);
        

        基本上就是:

        "SELECT" Select the rows    
        "CONCAT" Returns the string that results from concatenating (joining) all the arguments
        "GROUP_CONCAT" Returns a string with concatenated non-NULL value from a group
        

        【讨论】:

        • 请注意GROUP_CONCAT()group_concat_max_len 的限制。
        • 我不建议任何人使用这种 hacky 技术。
        【解决方案10】:
        <?php
        define('HOST','localhost');
        define('USER','root');
        define('PASS','');
        define('DB','dishant');
        
        $con = mysqli_connect(HOST,USER,PASS,DB);
        
        
          if (mysqli_connect_errno())
          {
           echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }
        
         $sql = "select * from demo ";
        
         $sth = mysqli_query($con,$sql);
        
        $rows = array();
        
        while($r = mysqli_fetch_array($sth,MYSQL_ASSOC)) {
        
         $row_array['id'] = $r;
        
            **array_push($rows,$row_array);**
        }
        echo json_encode($rows);
        
        mysqli_close($con);
        ?>
        

        aarray_push($rows,$row_array); 帮助构建数组,否则它会在 while 循环中给出最后一个值

        这项工作类似于 java

        StringBuilderappend 方法

        【讨论】:

          【解决方案11】:

          使用 FOR 循环的另一个选项:

           $sth = mysql_query("SELECT ...");
           for($rows = array(); $row = mysql_fetch_assoc($sth); $rows[] = $row);
           print json_encode($rows);
          

          唯一的缺点是循环 for 比 e.g. 慢。 while 或特别是 foreach

          【讨论】:

            【解决方案12】:

            例如 $result = mysql_query("SELECT * FROM userprofiles where NAME='TESTUSER'");

            1.) 如果 $result 只有一行。

            $response = mysql_fetch_array($result);
            echo json_encode($response);
            

            2.) 如果 $result 超过一行。您需要迭代行并将其保存到一个数组中并返回一个包含数组的json。

            $rows = array();
            if (mysql_num_rows($result) > 0) {
                while($r = mysql_fetch_assoc($result)) {
                   $id = $r["USERID"];   //a column name (ex.ID) used to get a value of the single row at at time
                   $rows[$id] = $r; //save the fetched row and add it to the array.
                }
            }    
            echo json_encode($rows);
            

            【讨论】:

              【解决方案13】:

              我也有同样的要求。我只想将结果对象打印成 JSON 格式,所以我使用下面的代码。我希望你能从中找到一些东西。

              // Code of Conversion
              $query = "SELECT * FROM products;";
              $result = mysqli_query($conn , $query);
              
              if ($result) {
              echo "</br>"."Results Found";
              
              // Conversion of result object into JSON format
              $rows = array();
              while($temp = mysqli_fetch_assoc($result)) {
                  $rows[] = $temp;
              }
              echo "</br>" . json_encode($rows);
              
              } else {
                  echo "No Results Found";
              }
              

              【讨论】:

              • 这个答案使用了糟糕的代码选项卡,并且由于在编码字符串之前添加了字符,输出将呈现为无效的 json。我没有看到这个答案说明了已接受的答案已经说过的任何内容。
              【解决方案14】:

              我是这样解决的

              $stmt->bind_result($cde,$v_off,$em_nm,$q_id,$v_m);
                  $list=array();
                  $i=0;
                  while ($cresult=$stmt->fetch()){    
              
              
                      $list[$i][0]=$cde;
                      $list[$i][1]=$v_off;
                      $list[$i][2]=$em_nm;
                      $list[$i][3]=$q_id;
                      $list[$i][4]=$v_m;
                      $i=$i+1;
                  }
                  echo json_encode($list);        
              

              这将作为结果集返回给 ajax 并通过在 javascript 部分中使用 json 解析,如下所示:

              obj = JSON.parse(dataX);
              

              【讨论】:

                【解决方案15】:

                我们可以像这样简化 Paolo Bergantino 答案

                $sth = mysql_query("SELECT ...");
                print json_encode(mysql_fetch_assoc($sth));
                

                【讨论】:

                • 我不认为你可以。
                【解决方案16】:

                代码:

                $rows = array();
                
                while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {
                
                 $row_array['result'] = $r;
                
                  array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
                }
                
                echo json_encode($rows);
                

                【讨论】:

                  【解决方案17】:
                  $array = array();
                  $subArray=array();
                  $sql_results = mysql_query('SELECT * FROM `location`');
                  
                  while($row = mysql_fetch_array($sql_results))
                  {
                      $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
                      $subArray[x]=$row['x'];
                      $subArray[y]=$row['y'];
                  
                  
                   $array[] =  $subArray ;
                  }
                  echo'{"ProductsData":'.json_encode($array).'}';
                  

                  【讨论】:

                  • 这个无法解释的帖子对这个页面有什么新价值?我看到了未加引号的键、已弃用的 mysql_ 调用和手动制作的 json 字符串。这个答案中有太多的否定。
                  【解决方案18】:

                  考虑到 mysql 中一般没有任何 NESTED json 对象等,制作自己的编码函数相当容易

                  首先,检索mysqli的函数产生一个数组:

                  function noom($rz) {
                      $ar = array();
                      if(mysqli_num_rows($rz) > 0) {
                          while($k = mysqli_fetch_assoc($rz)) {
                              foreach($k as $ki=>$v) {
                                  $ar[$ki] = $v;
                              }
                          }
                      }
                      return $ar;
                  }
                  

                  现在,将数组编码为 json 的函数:

                  function json($ar) {
                      $str = "";
                      $str .= "{";
                      $id = 0;
                      foreach($ar as $a=>$b) {
                          $id++;
                          $str .= "\"".$a."\":";
                          if(!is_numeric($b)) {
                              $str .= "\"".$b."\"";
                          } else {
                              $str .= $b;
                          }
                          
                          if($id < count($ar)) {
                              $str .= ",";
                          }
                      }
                      $str .= "}";
                      return $str;
                  }
                  

                  然后使用它:

                  <?php
                  $o = new mysqli(
                      "localhost",
                      "root",""
                  );
                  if($o->connect_error) {
                      echo "DUDE what are you/!";
                  } else {
                      $rz = mysqli_query($o,
                          "SELECT * FROM mydatabase.mytable"
                      );
                      $ar = noom($rz);
                      echo json($ar);
                  }
                  ?>
                  

                  【讨论】:

                    猜你喜欢
                    • 2011-11-23
                    • 2015-10-06
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-11-24
                    • 2013-04-27
                    • 2023-04-01
                    • 2019-09-09
                    • 2013-07-20
                    相关资源
                    最近更新 更多