tags:

views:

10

answers:

2

I am trying to run the following script (unsuccessfully):

$variables = $db->query("SELECT * FROM table1 WHERE Session_ID = '$sess1'");

while($row = $variables->fetch()) {

//FETCH DATA
$id= $row["ID"];
$info = $db->query("SELECT * FROM table2 WHERE ID = $id");

while($row2 = $info->fetch()) { 
    $name = $row2["FNAME"]." ".$row2["LNAME"]; }
    $phone = $row2["PHONE"];
}

//SEND CUSTOMER EMAIL
require("../email/email.php");                      
}

this returns the error: Fatal error: Call to a member function fetch() on a non-object in...

While I am able to "solve" the problem, it is ugly. Essentially I have to make several calls ahead of the one I'm trying below (which in theory should work).

Any ideas?

A: 

try this instead

    //prepare the query
    $variables = $db->prepare("SELECT * FROM table1 WHERE Session_ID = :sess1");
    $info = $db->prepare("SELECT * FROM table2 WHERE ID = :ID");

    //bind the variable :sess1 to $sess1
    $variables->bindParam(':sess1', $sess1, PDO::PARAM_STR);

    //execute the query 
    $variables->execute;

    //fetch the result
    $result = $variables->fetch(PDO::FETCH_ASSOC);

    //set $result['ID'] to a variable and bind it to the variable :ID in our second query
    $id = $result['ID'];
    $info->bindParam(':ID', $id, PDO::PARAM_INT);

    while($row2 = $info->fetch()) { 
        $name = $row2["FNAME"]." ".$row2["LNAME"]; }
        $phone = $row2["PHONE"];
    }

    //SEND CUSTOMER EMAIL
    require("../email/email.php");                      
    }
Catfish
@CATFISH - unfortunately a no-go; Parse error: syntax error, unexpected T_ECHO, expecting T_CATCH
JM4
Erm, as far as I can see, you only alter queries in prepared statements (which is OK, but beside the point), + forgetting to call an `execute`. How is that going to solve the problem?
Wrikken
A: 

As far as I can tell, you have to fetch all results from a resultset before you can issue a new query. If you're using MySQL, you can circumvent that by calling $db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);, but I would advice against it, as it makes your code less portable, and on of the major plusses of PDO, database-abstraction, is lost.

Wrikken
Thanks Wrikken - I dont like my solution but its pretty fast and works so I'll go with it for now I guess!
JM4
Note: I know with mysqli you can use stored results (perhaps you can with PDO as well but i have yet to be able to find it)
JM4
Those 'stored results' are probably the same thing as the `MYSQL_ATTR_USE_BUFFERED_QUERY`, it stores / buffers a resultset for later use, freeing up the database connection for the next query, at least as far as I understand their workings.
Wrikken