0

i used this script to convert all data to json by using json_encode

$response = array();
$con=mysqli_connect("localhost","root","","market");
// Check connection
if (mysqli_connect_errno())
  {
  die ("Failed to connect to MySQL: " . mysqli_connect_error());
  }
$myData = array();
$result = mysqli_query($con, "SELECT * FROM `item`");
while ($row = mysqli_fetch_assoc($result))
{
    $myData[] = $row;
}
echo json_encode($myData, JSON_UNESCAPED_UNICODE);

when I used this script the result is empty. I check the connection and query via write echo method inside while loop. the result written and not has problem in connection and query, because in each loop is give me the array.

while ($row = mysqli_fetch_assoc($result))
    {
        $myData[] = $row;
        echo json_encode($myData, JSON_UNESCAPED_UNICODE);
    }

And i want just one array for all my data I don't know where is the problem.

I hope my question is clear

Abdu Hawi
  • 79
  • 2
  • 14
  • 1
    Note: The object-oriented interface to `mysqli` is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface. Before you get too invested in the procedural style it’s worth switching over. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. – tadman Feb 15 '18 at 18:38
  • try to echo just $myData after loop without json_encode, to debug if problem is with $myData (empty?? - I am not sure how this could happen if if your second example is working) or json_encode – Dolfa Feb 15 '18 at 18:47
  • I echo just $myData after loop with out json_encode, I debug this not ** Notice: Array to string conversion** and echo **Array** word – Abdu Hawi Feb 15 '18 at 18:52
  • My bad, use var_dump($myData) or print_r($myData) instead. Error tells us that $myData is an array, but it could still be empty – Dolfa Feb 15 '18 at 19:38
  • **this result is from print_r** : Array ( [0] => Array ( [i_id] => 45 [i_name] => 2 [i_desc] => 2 [i_prush_pri] => 2 [i_unit] => 2 [i_img_name] => burger.jpg ) [1] => Array ... etc . **And this result from var_dump** array (size=15) 0 => array (size=6) 'i_id' => int 45 'i_name' => string '2' (length=1) 'i_desc' => string '2' (length=1) 'i_prush_pri' => string '2' (length=1) 'i_unit' => string '2' (length=1) 'i_img_name' => string 'burger.jpg' (length=10) 1 => ... etc – Abdu Hawi Feb 15 '18 at 21:20
  • So it seems that you have some data there, albeit in some array of array form. But that still should encode it somehow, see php.net/manual/en/function.json-encode.php for examples. Does json_encode print it as empty json ([]) or it doesnt print anything(that would point to some error - https://stackoverflow.com/questions/1475297/phps-white-screen-of-death ) ? – Dolfa Feb 16 '18 at 15:33

0 Answers0