user1649798
user1649798

Reputation: 903

Best practices using PDO queries to display data

Updating existing queries from mysql_* calls to PDO calls. Have a lot of instances where data is extracted from a DB and then used in various display capacities. To keep it simple, let's say all you want to do is make a vertical list of one column returned from a query. That same concept could populate an on screen table column, a drop down list, what ever but let's just say all that is needed is to display one data cell per line on a screen using PHP.

Using MySQL you could:

Include('./dbconnect.php);//assume it is set up with to include the correct DB
$query = 'SELECT C1 FROM T1';
$result = mysql_query($query);
mysql_close($dbconn);//assume $dbconn is correct from dbconnect.php
// what ever amount of code between here and there but the connection is closed
while($row = mysql_fetch_assoc($result)){
echo $row['C1']."<br>";//prints the results one data set per row
}
// what ever else you need to code after this

With PDO can you execute the query, save it as an array and close the connection neatly like the above example or do you have to wait until you run something like;

// The PDO connect, statement
// what ever amount of code between here and there but with connection still open
while($row = $stmt->(PDO::FETCH_ASSOC)){
echo($row['C1']."<br>";
}
$dbconn = null;  // finally close the connection after who knows how long
// what ever else you need to code after this

Another way to ask this question might be to ask if all the PDO attributes get values if you execute the statement something like:

$result = $stmt->execute;// assume the connection and statement were properly set up

Could you then set the connection to null, closing it and at some point later in the code just use something like:

While($row = $result->(PDO::FETCH_ASSOC)){
// what ever
}

And expect it to work?

Thanks

Upvotes: 0

Views: 315

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157914

let's just say all that is needed is to display one data cell per line on a screen using PHP.

$query = 'SELECT C1 FROM T1';
$stmt  = $pdo->query($query);
$data  = $stmt->fetchAll();
// here you can close the connection, though it's absolutely unnecessary.
foreach($data as $row){
    // what ever
}

Upvotes: 1

Related Questions