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.