简体   繁体   中英

How can I create a json object in php

I am working in android and php.

I want to return a json object to android program from php program.

If these is a entry in a database then it is working properly. But when there is no record in database then it goes wrong.

I would welcome suggestions

I want to make json object like this ([{"id":"5"}])

This is my php program:-

    $server = "localhost";
    $username = "root";
    $password = "";
    $database = "mymusic";

    $con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
    mysql_select_db($database, $con);
     $id=$_GET["id"];
     $pass=$_GET["password"];
    //$id='ram';
    //$pass='ram';
    $sql = "SELECT id FROM login where userid='$id' and password='$pass'";
    $result = mysql_query($sql) or die ("Query error: " . mysql_error());

    $records = array();
    if (mysql_num_rows($result)==0)
     {
      //what should i right here to make jsonobject like this:- ([{"id":"5"}])
       echo myjsono;
     }
     else
     {
       while($row = mysql_fetch_assoc($result)) 
       {
         $records[] = $row;
       }
       echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
     }

    ?>

How about something like this: (replace with your own variables)

if (empty($row)){
$arr = array('success' => 'false');
} else {
$arr = array('success' => 'true');
}
echo json_encode($arr);

If you want your android app to receive an object with a special id in the case of a not found condition I would return this:

{"id":"0"}

Then in your android app check if the id == 0 and that will tell you no records were found.

This is very correct solution for my question:-

$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
 $id=$_GET["id"];
 $pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();
if (mysql_num_rows($result)==0)
 {
  //  {"messages":{"message":[{"id":  "17","user": "Ryan Smith","text": "This is an example of JSON","time": "04:41"}]};}

  **echo '('.'['.json_encode(array('id' => 0)).']'.')';** //**note this**
 }
 else
 {
   while($row = mysql_fetch_assoc($result)) 
   {

     $records[] = $row;
   }
   mysql_close($con);
   echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
 }

//mysql_close($con);

//echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM