Reputation: 135
This is my Php code. I am new in php and I want to get proper responce of JSON.
$db_handle = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $db_handle )
{
die('Could not connect: ' . mysql_error());
}
else
$response["message"] = "Connected Succsessfully";
//echo json_encode($response);
$db_found = mysql_select_db($db, $db_handle);
// check for required fields
if($db_found)
{
// mysql inserting a new row
mysql_query('SET CHARACTER SET utf8');
$query = "SELECT * FROM users";
$result = mysql_query($query);
//iterate over all the rows
$emparray[] = array();
while($row = mysql_fetch_assoc($result)){
//iterate over all the fields
$emparray[] = $row;
}
echo json_encode($emparray);
And this is my responce :
[[],{"id":"1","username":"Liyari","password":"Karachi"},{"id":"12","username":"ssssss","password":"111111"},{"id":"121","username":"135","password":"Qasim"},{"id":"17","username":"nafees","password":"99999"},{"id":"134","username":"","password":""},{"id":"133","username":"","password":""},{"id":"135","username":"mustafa","password":"45612"},{"id":"131","username":"mustafa","password":"45612"},{"id":"132","username":"","password":""}]
Q) Why I am getting null array at the start of Response.
Upvotes: 1
Views: 390
Reputation: 33
When you write something like
$foo[] = $something;
in php, you are adding an element to the end of the array.
With
$emparray[] = array();
you are adding and array as first element, because $emparray
is not previously initialized, and that's because you get an empty array at the beginning of the response.
You should change
$emparray[] = array();
by
$emparray = array();
Upvotes: 3
Reputation: 11987
remove
$emparray[] = array();
or make it as
$emparray = array();
then it will work fine.
Upvotes: 3