Jump to content

[SOLVED] general question about pdo


devdavad

Recommended Posts

Alright I'm trying to execute this sql query (with postgresql of course) "SELECT event FROM calendar WHERE day = " . $day;

with this first example I got the information ok and everything

include("connection.php");
$sql = "SELECT event FROM calendar WHERE day = 27";
foreach($conn->query($sql) as $row) {
print $row["event"];
}
$conn = null;

but for some reason when that is re-written as a function for use in another script I get this error:

Fatal error: Call to a member function query() on a non-object

function getevents($day) {
$sql = "SELECT event FROM calendar WHERE day = " . $day;
foreach($conn->query($sql) as $event) { return $event["event"]; }
}

by the way both scripts include connection.php which has the connection information

Link to comment
https://forums.phpfreaks.com/topic/134602-solved-general-question-about-pdo/
Share on other sites

You need to build a result set and return it all at once, instead of having a return inside the foreach loop.  You also need to bring $conn into scope.  Try this:

 

function getevents($day) {
        global $conn;
$sql = "SELECT event FROM calendar WHERE day = " . $day;
$results = array();
        foreach($conn->query($sql) as $event) {
                $results[] = $event["event"];
        }
        return $results;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.