How to retrieve information from database and store in multidimensional array [closed]
What I am trying to do is create an array of calendar objects from a database.
The result I'm looking for would be something like this:
array(
array(
'id' => 111,
'title' => "Event3",
'start' => "$year-$month-10",
'url' => "http://example.com/"
),
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://example.com/"
)
)
I need the correct code that will generate a subarray from each database record. After the array is generated, I will json_encode
it.
Note the variables $year
and $month
would be supplied from other parts of my code.
Have you tried something like this?:
$mysqli = new mysqli ( 'Host', 'User', 'Pass', 'dB');
$myq = $mysqli ->query ( 'SELECT field1, field2, field3 FROM table' );
$arr_result = array();
while ( $myr = $myq->fetch_assoc () ) {
$array = array(
'field1' => $myr['field1'],
'field2' => $myr['field2'],
'field3' => $myr['field3'],
);
$arr_result[] = $array;
}
echo json_encode($arr_result);
If it's only the json_encode()
bit that's failing, it could be due to a character encoding issue. The json_encode()
function requires that all string members be valid UTF8 strings. From the json_encode()
documentation:
This function only works with UTF-8 encoded data.
If your relevant database objects aren't UTF8, you'll see the function call fail.
精彩评论