[php] How to build a JSON array from mysql database

Okay I have been racking my brain trying to build a JSON array from mysql. The array MUST be in the following format. I am using fullcalendar and want to make the events on the calendar dynamic. Below is the code that builds the array, but currently it does not get the information from mysql

$year = date('Y');
$month = date('m');

echo json_encode(array(

    //Each array below must be pulled from database
        //1st record
        array(
        'id' => 111,
        'title' => "Event1",
        'start' => "$year-$month-10",
        'url' => "http://yahoo.com/"
    ),

         //2nd record
         array(
        'id' => 222,
        'title' => "Event2",
        'start' => "$year-$month-20",
        'end' => "$year-$month-22",
        'url' => "http://yahoo.com/"
    )

));

This question is related to php mysql json

The answer is


Use this

$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).'}';

Just an update for Mysqli users :

$base= mysqli_connect($dbhost,  $dbuser, $dbpass, $dbbase);

if (mysqli_connect_errno()) 
  die('Could not connect: ' . mysql_error());

$return_arr = array();

if ($result = mysqli_query( $base, $sql )){
    while ($row = mysqli_fetch_assoc($result)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
   }
 }

mysqli_close($base);

echo json_encode($return_arr);

The PDO solution, just for a better implementation then mysql_*:

$array = $pdo->query("SELECT id, title, '$year-month-10' as start,url 
  FROM table")->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);

Nice feature is also that it will leave integers as integers as opposed to strings.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?