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
// $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
bit of bracket mis-matching going on there
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
{
// 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"));