Reputation: 103
I'm trying to make a function called query_select
using sort of a modified database class. I can get the information from it, and it works, but that's only in the function. Here's the code:
public function query_select($query)
{
try
{
$this->query = $this->pdo->prepare($query);
$this->success = $this->query->execute();
$result = $this->query->fetchAll();
foreach($result as $row)
{
echo $row['id'], '<br>', $row['username'], '<br>', $row['password'];
}
}
catch(PDOException $ex)
{
die($ex->getMessage());
}
$this->parameters = array();
}
So that displays this:
1
JoelE
123456
And I'm trying to do this:
public function query_select($query)
{
try
{
$this->query = $this->pdo->prepare($query);
$this->success = $this->query->execute();
$result = $this->query->fetchAll();
return $result;
}
catch(PDOException $ex)
{
die($ex->getMessage());
}
$this->parameters = array();
}
And then try something like this after I called the function in my page file:
foreach($result as $row)
{
echo $row['id'], '<br>', $row['username'], '<br>', $row['password'];
}
But I get this:
Notice: Undefined variable: result in C:\xampp\htdocs\index.php on line 8
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\index.php on line 8
Upvotes: 1
Views: 27
Reputation: 265271
You need to assign the value returned by the function to a variable first:
$result = query_select(...);
foreach($result as $row) {
echo $row['id'], '<br>', $row['username'], '<br>', $row['password'];
}
Upvotes: 3