Mudassar Saiyed Mudassar Saiyed - 19 days ago 6
JSON Question

Getting null array first and then getting actual result in php

In my script i am fetching data from database and storing it in array and output it in json. Everything is going correct just the first array I am getting is null and then the second array has the correct data. I don't understand why am I getting first null array.

My problem solves if I get correct result in array without the null array.
Here is the output I am getting

[[],{"url":"example.com\/sign_pdf\/PDFSign.pdf","name":"PDFSign.pdf","signer":"aman","sequence":"1","message":"Hello","flag":"0"}]


I don't need First null array. Why the hell am I getting that.

Here is the code.

if(($_GET['action'])&&($_GET['username'])&&($_GET['key'])) {

$select = $_GET['action'];
$username =$_GET['username']; //no default
$key= $_GET['key'];
if($key=='abcxyz'){
if($select=='select'){
/* connect to the db */
$connect = mysqli_connect('localhost','root','')or die("Couldn't connect to database!");
mysqli_select_db($connect,'sign') or die ("Couldn't find database");



$query ="SELECT * FROM path WHERE signer ='$username' ";



$result = mysqli_query($connect,$query);
$numrows=mysqli_num_rows($result);
$posts[] = array();
if($numrows!==0)
{

while($row = mysqli_fetch_array($result))
{
$post['url'] = $row['url'];
$post['name'] = $row['name'];
$post['signer'] = $row['signer'];
$post['sequence'] = $row['sequence'];
$post['message'] = $row['message'];
$post['flag'] = $row['flag'];
array_push($posts, $post);
}

header('Content-type: application/json');
echo json_encode($posts);


}
}
}
}

Answer

You are creating array(array()) by $posts[] = array();

Replace this:

$posts[] = array();

with

$posts = array();

$posts = array(); will create a null array() and not array(array())

Comments