[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 967
  • Last Modified:

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
0
xomn
Asked:
xomn
  • 2
1 Solution
 
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
 
aidinetCommented:
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:
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

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now