使用PDO查询显示数据的最佳做法

时间:2013-08-07 19:50:09

标签: pdo

从mysql_ *更新现有查询调用PDO调用。有很多实例从数据库中提取数据,然后用于各种显示容量。为了简单起见,让我们说你要做的就是从查询中返回一列的垂直列表。同样的概念可以填充一个屏幕表列,一个下拉列表,但是只需说明所需要的就是使用PHP在屏幕上每行显示一个数据单元。

使用MySQL你可以:

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

使用PDO,您可以执行查询,将其保存为数组并像上面的示例一样整齐地关闭连接,或者您必须等到运行类似的内容;

// 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

提出这个问题的另一种方法可能是询问所有PDO属性是否在执行以下语句时获取值:

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

然后你可以将连接设置为null,关闭它,稍后在代码中稍后使用类似的东西:

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

期待它的运作?

由于

1 个答案:

答案 0 :(得分:1)

  

我们只需说明所需要的是使用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
}