Fatal error: Call to a member function query() on a non-obje
Posted: Mon Sep 19, 2011 5:11 am
I try the following example , but get Fatal error: Call to a member function query() on a non-object How to fix the problem??
Code: Select all
<?php
function dbConnect($usertype, $connectionType = 'mysqli') {
$host = 'localhost';
$db = 'test';
if ($usertype == 'read') {
$user = 'psread';
$pwd = 'read12';
} elseif ($usertype == 'write') {
$user = 'pswrite';
$pwd = 'write12';
} else {
exit('Unrecognized connection type');
}
if ($connectionType == 'mysqli') {
return new mysqli($host, $user, $pwd, $db) or die ('Cannot open database');
} else {
try {
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e) {
echo 'Cannot connect to database';
exit;
}
}
}
Code: Select all
<?php
require_once('../includes/connection.inc.php');
// connect to MySQL
$conn = dbConnect('read');
// prepare the SQL query
$sql = 'SELECT * FROM images';
// submit the query and capture the result
$result = $conn->query($sql) ;
// find out how many records were retrieved
$numRows = $result->num_rows;
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Connecting with MySQLi</title>
</head>
<body>
<p>A total of <?php echo $numRows; ?> records were found.</p>
<table>
<tr>
<th>image_id</th>
<th>filename</th>
<th>caption</th>
</tr>
<?php while ($row = $result->fetch_assoc()) { ?>
<tr>
<td><?php echo $row['image_id']; ?></td>
<td><?php echo $row['filename']; ?></td>
<td><?php echo $row['caption']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>