nilsolofsson
nilsolofsson

Reputation: 96

Php SELECT-query returning null on fields that's not null

I have a php-file that returns a JSON-array that i will use in conjunction with javascript to populate a website with news from a sql-database. The sql-query works on the server and returns the information i want. While the php-file returns this:

[{"rubrik":null,"ingress":null,"datum":"2014-11-10 16:11:54},{"rubrik":null,"ingress":null,"datum":"2014-11-28 23:17:02"}]

The dates is correct. although the fields "rubrik" and "ingress" have some text in them and are not null. The database looks like this:

NAME    TYPE            COLLATION               NULL
rubrik  varchar(254)    latin1_swedish_ci       No
ingress text            latin1_swedish_ci       No
nyhet   text            latin1_swedish_ci       No
datum   timestamp                               No

The field "nyhet" is not going to be needed right now.

And this is how my php-file looks like.

$result = mysqli_query($con, "SELECT rubrik, ingress, datum FROM svensta_news");

$return_arr = array();

while ($row = mysqli_fetch_array($result))
{
    $row_array['title']=$row['rubrik'];
    $row_array['ingress']=$row['ingress'];
    $row_array['date']=$row['datum'];

    array_push($return_arr, $row);
}

echo json_encode($return_arr);

I cant understand what is wrong here any why my php returns null on fields that's not null.

EDIT: Information about how data looks like in the DB

nyhetsId    rubrik          ingress         news        date
120         sometitle       Someingress     Null        2014-11-10 16:11:54
122         sometitle2      Someingress     Null        2014-11-28 23:17:02

Upvotes: 2

Views: 2002

Answers (3)

Alex
Alex

Reputation: 626

array_push($return_arr, $row);

Doesn't get values from while condition, since you declare $return_arr = array();

You should use :

$return_arr['title']=$row['rubrik'];
$return_arr['ingress']=$row['ingress'];
$return_arr['date']=$row['datum'];

in your while condition to get the values.

Query using MySQL COLLATE :

SELECT rubrik COLLATE latin1_swedish_ci AS rubrik, ingress COLLATE latin1_swedish_ci AS ingress, datum COLLATE latin1_swedish_ci AS datum FROM svensta_news

Upvotes: 0

Binu
Binu

Reputation: 23

initialize $row_array as an array()

also change code as

array_push($return_arr, $row_array);

Upvotes: 0

ryvasquez
ryvasquez

Reputation: 158

I didnt test it but I think this should work.

$result = mysqli_query($con, "SELECT rubrik, ingress, datum FROM svensta_news");

$return_arr = array();

while ($row = mysqli_fetch_array($result))
{   
    $return_arr[] = array(
        'title' => $row['rubrik'],
        'ingress' => $row['ingress'],
        'date' => $row['datum'] 
    );
}

echo json_encode($return_arr);

Upvotes: 1

Related Questions