questions from a Newbie 🙂
I am trying to convert my MySQL query syntax into PDO but having some issues getting started.
I have an included file in my page called dbc.php. contains the code:
define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", "dbuser"); // set database user
define ("DB_PASS","dbpass"); // set database password
define ("DB_NAME","dbname"); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
My Page code is then:
<?php
include 'dbc.php';
page_protect();
function get_users($db) {
$getusers = $db->query('SELECT employeeid, fullname FROM Persons order by fullname asc');
}
?>
I want to display the table output with the following code:
<table>
<tr>
<th> Full Name</th>
</tr>
<?
while($row = $getusers->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td>
<?
echo $row['fullname'];
?>
</td>
</tr>
<?
}
?>
</table>
This currently outputs the error:
Fatal error: Call to a member function fetch() on a non-object in /home/she/public_html/versionfour/people.php on line 170
where line 170 is my ‘ while($row = $getusers->fetch(PDO::FETCH_ASSOC)) ‘ statement.
I know I am missing something simple here, probably for not completely understanding PDO as yet.
any help is apprecaited.
Thanks and regards,
R
This issue you have relates to the scope of the “$getUsers” variable. Because the function does not return its value the HTML file cannot access this and the fetch() method is trying to be called on a undefined value, hence the “non-object” part within the error.
You should also consider some error checking to ensure that the returned db result is actually a PDO result or you may still encounter this issue.