将现有查询从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
}
并期望它能工作吗?
谢谢
我们只需要使用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
}