When i run my code i receive the following error:
Fatal error: Call to a member function fetch() on a non-object in C:\Program Files\EasyPHP-5.3.8.0\www\Practice\staff.php on line 20
The code that causes the error is:
<?php
require_once "db_connect.php";
$dbh = db_connect ();
$dbh->exec ("CREATE TABLE Staff(
UserId int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(UserId),
Username varchar(65) NOT NULL,
Password varchar(65) NOT NULL
)");
$dbh->exec ("INSERT INTO Staff
(UserId, Username, Password)
VALUES (0000, 'Ben', 'Password')");
$sql = "SELECT * FROM Staff";
$stmt = $dbh->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
foreach($result as $key=>$val){
echo "$val";
}
?>
The files also included are:
db_connect.php
<?php
function db_connect ()
{
include'db_connection.inc';
$dbh = new PDO("mysql:host=127.0.0.1;$database", $user, $password);
return ($dbh);
}
?>
and :
db_connection.inc
<?php
$host = 'mysql:host=127.0.0.1;';
$user = 'root';
$password = 'mysql';
$database = 'library_db';
?>
I know the error states what is wrong but i am not sure which PDO fetch command i should be using or if there is anything else i am doing wrong.
What i want for it to do is print out the values of the record in the Staff table.
Any help is appreciated, thanks.