【问题标题】:Best practices using PDO queries to display data使用 PDO 查询显示数据的最佳实践
【发布时间】:2015-09-27 17:57:00
【问题描述】:

将现有查询从 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

您能否将连接设置为空,关闭它,稍后在代码中使用类似的东西:

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

并期望它起作用?

谢谢

【问题讨论】:

  • 您注意到文档中的fetchAll() 函数了吗?
  • 为什么关闭连接是您如此关心的问题?

标签: pdo


【解决方案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
}

【讨论】:

  • 谢谢 Y.C.S.这就是我一直在寻找的。因此,$data 使用 PDO 有效地变成了一个数组,就像使用 $result = ... 使用 mysql_* 一样。是这样看的吗?
猜你喜欢
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 2015-12-02
相关资源
最近更新 更多