使用带有准备好的语句的 PDO 并在 foreach 中执行时,如何在 smarty 中显示数据?
How to display data in smarty when using PDO with prepared statement and executing inside foreach?
$dbh = new PDO($dsn, $user, $password, array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
$selectNumberTitle = $dbh->prepare("SELECT AdvertNumber, AdvertTitle FROM `adverts` WHERE AdvertNumber = ? ");
foreach ($advertnumber as $i => $number) {
$selectNumberTitle->execute(array($number));
foreach ($selectNumberTitle as $row) {
echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
}
}
以上代码运行良好。我在 smarty 中需要相同的输出。
您将要显示的数据保存在一个变量中,例如数组。在那之后你assign this variable to smarty。所以,你把这个问题分成两个:
- 从数据库中读取数组中的数据。
- 在您的 smarty 模板中显示变量(数组)。
$selectNumberTitleMerge = array();
foreach ($advertnumber as $i => $number) {
$selectNumberTitle->execute(array($number));
foreach ($selectNumberTitle as $row) {
$selectNumberTitleMerge[] = $row;
echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
}
}
$smarty->assign('selectNumberTitleMerge', $selectNumberTitleMerge);
我的模板中的代码:
{foreach $selectNumberTitleMerge as $r}
{$r.AdvertNumber})
{$r.AdvertTitle}
<br>
{foreachelse}
.. no results ..
{/foreach}
$dbh = new PDO($dsn, $user, $password, array(
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
$selectNumberTitle = $dbh->prepare("SELECT AdvertNumber, AdvertTitle FROM `adverts` WHERE AdvertNumber = ? ");
foreach ($advertnumber as $i => $number) {
$selectNumberTitle->execute(array($number));
foreach ($selectNumberTitle as $row) {
echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
}
}
以上代码运行良好。我在 smarty 中需要相同的输出。
您将要显示的数据保存在一个变量中,例如数组。在那之后你assign this variable to smarty。所以,你把这个问题分成两个:
- 从数据库中读取数组中的数据。
- 在您的 smarty 模板中显示变量(数组)。
$selectNumberTitleMerge = array();
foreach ($advertnumber as $i => $number) {
$selectNumberTitle->execute(array($number));
foreach ($selectNumberTitle as $row) {
$selectNumberTitleMerge[] = $row;
echo $row['AdvertNumber'] . ') ' . $row['AdvertTitle'] . "<br/>";
}
}
$smarty->assign('selectNumberTitleMerge', $selectNumberTitleMerge);
我的模板中的代码:
{foreach $selectNumberTitleMerge as $r}
{$r.AdvertNumber})
{$r.AdvertTitle}
<br>
{foreachelse}
.. no results ..
{/foreach}