Search code examples
phparraysinternal-server-error

persistent php 500 error


I'm new in PHP and I'm trying to run a simple php script. It's connecting to a LAPP with PHP 5.6 and I have set a simple test database

Peugeot     6666666
Mercedes    57127
Skoda       9000
Volvo       29000
Bentley     350000
Citroen     21000
Hummer      41400
Volkswagen  21600

No problems with the database. Problem is with php script which is connecting succesfully to database but displays a persistent 500 error.

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
#   $db = pg_connect("sslmode=require host=$host port=5432 dbname=$database user=$user password=$pass");
   if(!$db){
#      echo "Error : Unable to open database\n";
   } else {
#      echo "Opened database successfully\n";
   }

   $sql =<<<EOF
      SELECT * from Cars;
EOF;

   $ret = pg_query($db, $sql);
   if(!$ret){
      echo pg_last_error($db);
      exit;
   } 
#   $myarray = array()
    while($row = pg_fetch_row($ret)){
      $myarray[] = $row;
   }

#   echo json_encode($myarray, JSON_NUMERIC_CHECK);
    echo $myarray
#       echo "Operation done successfully\n";


    pg_close($db);
?>

The two lines

error_reporting(E_ALL);
ini_set('display_errors', '1');

as well as the line in my php.ini file

display_errors = On

don't make a difference on having the annoying 500 internal error. Taking my code manually line by line I noticed that defining the array( $myarray = array()) as well when i echo it(echo $myarray) gives me the error. The only workaround is using the json_encode which I would like to skip. So I'm having two questions.

*Why am I still having a general 500 error?

*And why is defining the array and just echo it crashes?


Solution

  • your echo $myarray doesn't have ; at end. Also its good practice to declare your variables before using them. So, use $myarray = array(); before using it in while loop.