0

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

并期望它起作用?

谢谢

4

1 回答 1

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
}
于 2013-08-07T20:02:22.480 回答