I'm going through the process of trying to catch up on PHP and figure out the language relatively quickly. Going through books, I'm trying to write some scripts that are very simple and will work with the Web Server I'm using (godaddy). The problem is, the code in the books is not working correctly. I keep having the same errors. I've been able to connect to the database but each time I write some simple PHP to pull from or search the database I'm getting an error.
Note, I've been able to connect to the database and pull data and display data but the below code comes up with the following error:
Fatal error: Call to a member function query() on a non-object in '..../index.php' on line 13
The code is the following:
<?php
require 'formhelpers.php';
$host = "xxxxxxxxxxxxxx.db.xxxxxxxxx.hostedresource.com";
$user = "xxxxxxxxxxxxxx";
$pass = "xxxxxxxxxxxxxx";
$db = "xxxxxxxxxxxxxx";
$connection = mysql_connect($host, $user, $pass) or die("Unable to connect!");
mysql_select_db($db) or die("Unable to connect!");
$dish_names = array();
$res = $db->query('SELECT dish_name FROM dishes');
while ($row = $res->fetchRow()) {
$dish_names[] = $row['dish_name'];
}
if ($_POST['_submit_check']) {
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
function show_form($errros = '') {
global $db;
if ($errors) {
print 'You need to correct the following errors: <ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print '<form method="POST" action="'.$SERVER['PHP_SELF'].'">';
print '<table>';
print '<tr><td>Dish:</td><td>';
input_select('dish_name', $_POST, $GLOBALS['dish_names']);
print '</td></tr>';
print '<tr><td colspan="2"><input type="submit" value="Search Dishes">';
print '</td></tr>';
print '</table>';
print '<input type="hidden" name="_submit_check" value="1"/>';
print '</form>';
}
function validate_form() {
$errors = array();
if (! array_key_exists($_POST['dish_name'], $GLOBALS['dish_names'])) {
$erros[] = 'Please select a valid dish.';
}
return $errors;
}
function process_form() {
global $db;
$dish_name = $GLOBALS['dish_name'][$_POST['dish_name']];
$dish_info = $db->getRow('SELECT dish_id, dish_name, price, is_spicy FROM dishes WHERE dish_name = ?', array($dish_name));
if (count($dish_info) > 0) {
print '<ul>';
print "<li> ID: $dish_info[dish_id]</li>";
print "<li> Name: $dish_info[dish_name]</li>";
print "<li> Price: $dish_info[price]</li>";
print "<li> Is Spicy: $dish_info[is_spicy]</li>";
print '</ul>';
} else{
print 'No dish matches.';
}
}
?>
So the error occurs on the line
$res = $db->query('SELECT dish_name FROM dishes');
This is where I keep getting errors, with the $db->getAll('SQL Statement') or the $db ->query('SQL Statement')
Can somebody help me out because I'm understanding the errors that's happening. Does it have to do with the server that's reading the PHP?
Please respond. Cheers.