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
xomnAsked:
Who is Participating?
 
aidinetConnect With a Mentor Commented:
function print_JSON($table_name, $column_names )
{
    // output is a JSON array of objects,
    // where each object represents a row of the table
$args = func_get_args ( )  ;
$args = array_shift($args );
$query = " SELECT `" . join($args, "`,`" ) . "` FROM `$table_name` ");
$rowsArr=array();
  if ($result= mysql_query($query)) {
     while ($row = mysql_fetch_array($result))  {
      $rowElements=array();
      foreach(  $row as $key=>$value){
            $rowElements[]="'$key':'$value'";
      }
      $rowStr="{".join($rowElements,",")."}"
      $rowsArr[] = $row;
     }
  }
 $JSON_STR= "[".join($rowsArr,",")."]";
  print $JSON_STR;
}
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
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"));
0
 
SyntheticsCommented:
bit of bracket mis-matching going on there
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.