-3
<?php
require_once 'connect.php' ;

$sql = "SELECT Title,Date,Time,Location,image_url FROM events ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {


    $data = array();
    while($row = $result->fetch_assoc()) {
       $data['events'] = $row ;

    }

} 


echo json_encode($data); 
header('Content-Type: application/json');

?> 
Aftab H.
  • 1,517
  • 4
  • 13
  • 25

1 Answers1

5

Insert entries in the list, with few minor suggestions

require_once 'connect.php' ;

$sql = "SELECT Title,Date,Time,Location,image_url FROM events ";

$result = $conn->query($sql);

// Move $data declaration up for zero result.
$data = array('events' => []);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
       // Insert $rows in events array
       $data['events'][] = $row ;

    }
} 

// Send headers first before sending any data
header('Content-Type: application/json');
echo json_encode($data); 
anwerj
  • 2,386
  • 2
  • 17
  • 36
  • 1
    It should not, check you php error reporting for any other error, enable all errors. – anwerj Jan 29 '18 at 19:21
  • 1
    Nothing wrong with the code presented above in this answer. A blank page is most likely user error on Sandra's part due to sloppy copy/pasting. – IncredibleHat Jan 29 '18 at 19:31
  • Then what i can do? – Sandra Khazaal Jan 29 '18 at 19:32
  • @anwerj Warning: Cannot modify header information - headers already sent by (output started at /home/abbassne/public_html/DoctorMobileApp/connect.php:16) in /home/abbassne/public_html/DoctorMobileApp/Events.php on line 21 – Sandra Khazaal Jan 29 '18 at 20:02
  • @anwerj then i tried removing json header ..then also get me a blank page – Sandra Khazaal Jan 29 '18 at 20:03
  • Remove any `echo` or `print_r` from your connect.php(line 16) file, go through this to understand more.https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php – anwerj Jan 29 '18 at 20:58
  • @anwerj it was Whitespace after ?> in connect.php line 16..I've removed the space and keep ?> ..it gets me raw data empty again and SyntaxError: JSON.parse: unexpected end of data at line 5 column 1 of the JSON data – Sandra Khazaal Jan 29 '18 at 21:59
  • @anwerj also i get through the link .. and says for my case Whitespace after ?> If the error source is mentioned as behind the closing ?> then this is where some whitespace or raw text got written out. The PHP end marker does not terminate script executation at this point. Any text/space characters after it will be written out as page content still. It's commonly advised, in particular to newcomers, that trailing ?> PHP close tags should be omitted. This eschews a small portion of these cases. (Quite commonly include()d scripts are the culprit.) – Sandra Khazaal Jan 29 '18 at 22:00
  • @anwerj so i tried to ommit ?> from connect.php but it stays the same with raw data empty and syntax error for json part – Sandra Khazaal Jan 29 '18 at 22:02