0

I try to fetch some data from a database with code below. There is a generic configuration file for connection details.

config.inc.php

<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

try {
        $connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
        die("OOPs something went wrong");
    }

?>

There is a separated file to perform database queries.

query.inc.php

<?php

  require_once('config.inc.php');
  $sql = 'SELECT name from table';
  $statement = $connection->prepare($sql);
  $statement->execute();
  if($statement->rowCount())
  {
    $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
    header('Content-type: application/json');
    echo json_encode($row_all);         
  }  
  elseif(!$statement->rowCount())
  {
    echo "no rows";
  }

?>

It throw HTTP ERROR 500 instead of the JSON formatted string. As I see code is valid syntactically and cannot found semantic error. Configuration is also valid, I tested it with another script.

appkovacs
  • 97
  • 1
  • 1
  • 9
  • 1
    what error it logs? http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php – cske Nov 19 '16 at 19:59
  • @cske : I found the problem. Variable `$connection` was undefined, because it was initialized in config as `$conn`. – appkovacs Nov 19 '16 at 20:33
  • 1
    If you can answer this, do post an answer. Otherwise this question doesn't help anyone. – tadman Nov 19 '16 at 21:31

1 Answers1

0

I found the problem. Variable $connection was undefined, because it was initialized in config as $conn. You can use code below for debugging:

error_reporting(E_ALL);
ini_set('display_errors', '1');
appkovacs
  • 97
  • 1
  • 1
  • 9