I am trying to get the basics down of using REST services. I am following along to this example and trying to get it to work with my sql database. I am basing my api.php file off some of the re written code in the comments. I understand that only my client.php page should be getting viewed by the web, but I get a blank page when viewing either of the files them in the browser. Everything works fine when the values are hardcoded like in the example, but when trying to call the values from a database it seems to break.
client.php
<html>
<body>
<?php
if (isset($_GET["action"]) && isset($_GET["id"]) && $_GET["action"] ==
"get_app")
{
$app_info = file_get_contents('http://localhost:8888/api.php?
action=get_app&id=' . $_GET["id"]);
$app_info = json_decode($app_info, true);
?>
<table>
<tr>
<td>App Name: </td><td> <?php echo $app_info["app_name"] ?></td>
</tr>
<tr>
<td>Price: </td><td> <?php echo $app_info["app_price"] ?></td>
</tr>
<tr>
<td>Version: </td><td> <?php echo $app_info["app_version"] ?></td>
</tr>
</table>
<br />
<a href="http://localhost:8888/client.php?action=get_app_list" alt="app
list">Return to the app list</a>
<?php
}
else // else take the app list
{
$app_list = file_get_contents('http://localhost:8888/api.php?
action=get_app_list');
$app_list = json_decode($app_list, true);
?>
<ul>
<?php
foreach ((array) $app_list as $app): ?>
<li>
<a href=<?php echo "http://localhost:8888/client.php?
action=get_app&id=" . $app["id"] ?> alt=<?php echo "app_" . $app_["id"] ?>>
<?php echo $app["name"] ?></a>
</li>
<?php endforeach;
?>
</ul>
<?php
} ?>
</body>
</html>
api.php
<?php
/*DB settings*/
ini_set('display_errors',1);
error_reporting(E_ALL);
define("MYSQL_HOST", "localhost");
define("MYSQL_USER", "root");
define("MYSQL_PASS", "");
define("MYSQL_DATABASE", "test");
$results=array();
$result=array();
function get_app_by_id($id)
{
$sql = "SELECT * from apps where id=$id";
try {
$dbh = new
PDO("mysql:host=".MYSQL_HOST.";dbname=".MYSQL_DATABASE.";charset=utf8",
MYSQL_USER, MYSQL_PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
} catch(PDOException $e) {
}
$app_info = $result;
return $app_info;
}
function get_app_list()
{
$sql = "SELECT * FROM apps";
try {
$dbh = new
PDO("mysql:host=".MYSQL_HOST.";dbname=".MYSQL_DATABASE.";charset=utf8",
MYSQL_USER, MYSQL_PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
} catch(PDOException $e) {
}
$app_list = $results;
return $app_list;
}
?>