PHP& MYSQL:获取所有列,从行中选择*并对结果进行json编码

时间:2014-11-19 16:05:04

标签: php mysql json printing encode

我正在尝试从mysql中获取数组并使用其值打印每个列。

这是我到目前为止所做的:

获取所有列:

$query = "SHOW COLUMNS FROM user_settings";
$resultx = mysql_query($query);$temp=0;$p = array();


while ($row = mysql_fetch_array($resultx)) {
    $p[$temp] = $row["Field"];$temp++;
}

Foreach列名称获取数据,其中用户ID = $ SESSION [' id']

foreach ($p as $f) {

        $json = array();
        $newquery = "SELECT * FROM user_settings WHERE uid = '" . $_SESSION['id'] ."'";
        $newresult = mysql_query($newquery);


        while($newrow = mysql_fetch_array($newresult)) {
                $json[$f] = $newrow[$f];
        }

        print json_encode($json);


    }

这很好用。问题是打印的阵列是这样的:

{"column1":"data"}{"column2":"data"}{"column3":"data"}

相反我希望json编码打印

[{"column1":"data","column2":"data","column3":"data"}}

2 个答案:

答案 0 :(得分:4)

您可以删除所有这些,因为它是多余的。

$query = "SHOW COLUMNS FROM user_settings";
$resultx = mysql_query($query);$temp=0;$p = array();

while ($row = mysql_fetch_array($resultx)) {
    $p[$temp] = $row["Field"];$temp++;
}

同样删除foreach循环,这样我们只剩下查询和while循环查询。

$json = array();
$newquery = "SELECT * FROM user_settings WHERE uid = '" . $_SESSION['id'] ."'";
$newresult = mysql_query($newquery);

print json_encode(mysql_fetch_assoc($newresult));

这应该使json_encode()函数编码多维结果数组。

还尝试删除mysql_ *函数并使用mysqli_ *函数或PDO,因为mysql_ *函数已被折旧。

答案 1 :(得分:3)

试试这个:

  $newquery = "SELECT * FROM user_settings WHERE uid = '" . $_SESSION['id'] ."'";
  $newresult = mysql_query($newquery);

  print json_encode(mysql_fetch_array($newresult));

我认为你不需要休息。