简体   繁体   English

PHP从MySQL获取所有值按列到json_encode

[英]php get from mysql all values by column to json_encode

I must put to json_encode all values of specifed mysql table column 我必须将指定的mysql表列的所有值都放入json_encode

$fromdate       = $_GET['fromdate'];
$getrezhiredh = safe_query("
    SELECT rezhour FROM rezhiredhours 
    WHERE rezdate = '".$fromdate."' ORDER BY rezhour
");

$rows = array();
while($r = mysql_fetch_assoc($getrezhiredh)) {
    $rows[] = $r;
}

print json_encode($rows);

With code above i have one problem. 与上面的代码我有一个问题。 This code return result only when in table we have one row with selected data. 仅当表中有一行包含选定数据时,此代码才返回结果。 In this case json_encode() result is 在这种情况下,json_encode()结果为

[{"rezhour":"1"}] [{ “rezhour”: “1”}]

But when table have more than one row with selected data result don't return anything but 但是,当表中的数据结果超过一行时,除了

[]

How put to json_encode() all values selected from table? 如何将所有从表中选择的值放入json_encode()?


EDIT: 编辑:

I just wonder why in case when we have more rows in table with selected data, result don't give as example below 我只是想知道为什么在表中有更多行包含选定数据的情况下,结果如下所示

[{"rezhour": { [0] => "1",[1] => "4" }] [{“ rezhour”:{[0] =>“ 1”,[1] =>“ 4”}]

Instead in result we have "[]" 结果是我们有“ []”


Thank You in advance. 先感谢您。

try changing 尝试改变

mysql_fetch_assoc($getrezhiredh)

to

mysql_fetch_object($getrezhiredh)

Results from mysql_fetch_assoc are different than you think. mysql_fetch_assoc结果与您想象的不同。 Each row is more or less like this: 每行或多或少是这样的:

array(1)
    "rezhour" => "1"

So you access the data it like this: 因此,您可以像这样访问数据:

while($r = mysql_fetch_assoc($getrezhiredh)) {
    $rows[] = $r["rezhour"];
}

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

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