0

I am Using Following code php array to encode Json

$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";

        $result = mysql_query($query) or die('Errant query:  ' . $query);
        $numResults = mysql_num_rows($result);
        if ($numResults > 0)
        {
            $data = array();
            while ($row = mysql_fetch_assoc($result))
            {
                $data = $row;

            }
        echo json_encode($data);
    }

IT gives Me result like

{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}

But I wanted To result like

{"SignIn":[{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}],"errors":[],"totalNumberOfRecords":1,"responseCode":"00000"}

How Can I do That

Or Suggest Me any other Method to do that

Shankar
  • 113
  • 2
  • 13
  • Add required keys to your `$data` array – u_mulder Mar 10 '17 at 07:40
  • and stop using mysql_* extension; http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – hassan Mar 10 '17 at 07:41
  • 1
    dont' use `mysql`, it's been deprecated and in PHP7 removed, use `mysqli` or `PDO`. **never ever ever ever** store plain text passwords! use `password_hash()` and `password_verify()`, and use parameterized statements to protect your code from **SQL Injection attacks**. – Franz Gleichmann Mar 10 '17 at 07:52

2 Answers2

0

You need to do something like below to get the desired output.

$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";

        $result = mysql_query($query) or die('Errant query:  ' . $query);
        $numResults = mysql_num_rows($result);
        if ($numResults > 0)
        {
            $data = array();
            while ($row = mysql_fetch_assoc($result))
            {
                $data[] = $row;
            }
        $result = ['SignIn' => $data, 'totalNumberOfRecords' => $numResults, 'errors' => [], 'responseCode' => 0000];
        echo json_encode($result);
        exit;
    }
Naincy
  • 2,953
  • 1
  • 12
  • 21
0

You have to store all information in a array to get what you want. For example,

$data = array("id" =>"26","fname"=>"Shankar","lname"=>"Salunkhe","category_name"=>"2");

$array = array("SignIn" => $data, "errors" => [], "totalNumberOfRecords" => 1,"responseCode" => "00000");

$result = json_encode($array);
Abhinav Gupta
  • 511
  • 4
  • 12