Link to home
Start Free TrialLog in
Avatar of xomn
xomn

asked on

simple PHP/MySQL to JSON function

I want a PHP function like this:
// $table_name is the name of an MySQL table
// $column_name is the name of a column in that table
// optional arguments after $column_name are additional table names
function print_JSON($table_name, $column_name /* ... optionally more column names... */) {
    // output is a JSON array of objects,
    // where each object represents a row of the table
}
Thanks
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

function print_JSON($table_name, $column_names )
{
    // output is a JSON array of objects,
    // where each object represents a row of the table
  $sql = " SELECT `" . JOIN($column_names, "`,`" ) . "` FROM $table_name ");
  $res = array();
  if ($rows = mysql_query($sql))
  {
     while ($row = mysql_fetch_assoc($rows))
     {
         $res[] = $row;
     }
  }
  return $res;
}

call sample:
$rows = print_JSON("table_name", array("col1", "col2", "col3"));
bit of bracket mis-matching going on there
ASKER CERTIFIED SOLUTION
Avatar of aidinet
aidinet

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I see, I had a ) too much in the $sql = "..." line:

function print_JSON($table_name, $column_names )
{
    // output is a JSON array of objects,
    // where each object represents a row of the table
  $sql = " SELECT `" . JOIN($column_names, "`,`" ) . "` FROM $table_name ";
  $res = array();
  if ($rows = mysql_query($sql))
  {
     while ($row = mysql_fetch_assoc($rows))
     {
         $res[] = $row;
     }
  }
  return $res;
}


thanks to Synthetics for pointing out.