我正在尝试使用PDO重写此脚本:
从数据库中获取值
mysql_select_db($database_db_FPF, $db_FPF);
$query_rsWorksMenu = "SELECT works.year, GROUP_CONCAT(workstitle.title) as titulos, GROUP_CONCAT(workstitle.id_title) as links FROM works JOIN workstitle ON works.id_year = workstitle.id_year GROUP BY works.year ORDER BY works.year DESC";
$rsWorksMenu = mysql_query($query_rsWorksMenu, $db_FPF) or die(mysql_error());
$row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu);
显示值
<ul>
<?php do { ?>
<li><span><?php echo $row_rsWorksMenu['year']; ?></span>
<ul>
<?php
$titulos = explode(",", $row_rsWorksMenu['titulos']);
$links = explode(",", $row_rsWorksMenu['links']);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><a href="works.php?id=<?php echo $link; ?>"><?php echo $titulo; ?></a></span></li>
<?php } ?>
</ul>
</li>
<?php }while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu)); ?>
</ul>
到目前为止我得到了什么:
从数据库中获取值:
$stmt2 = $conn->prepare('SELECT works.year, GROUP_CONCAT(workstitle.title) as titulos, GROUP_CONCAT(workstitle.id_title) as links FROM works JOIN workstitle ON works.id_year = workstitle.id_year GROUP BY works.year ORDER BY works.year DESC');
$stmt2->execute();
$result2 = $stmt2->setFetchMode(PDO::FETCH_OBJ);
显示值
<ul>
<?php do { ?>
<li><span><?php echo $result2->year; ?></span>
<ul>
<?php
$titulos = explode(",", $result2->titulos);
$links = explode(",", $result2->links);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><a href="works.php?id=<?php echo $link; ?>"><?php echo $titulo; ?></a></span></li>
<?php } ?>
</ul>
</li>
<?php }while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu)); ?>
</ul>
问题是我不知道如何处理这一行:
}while ($row_rsWorksMenu = mysql_fetch_assoc($rsWorksMenu));
更新:
我改变了我的代码:
$stmt2 = $conn->prepare('...query...');
$stmt2->execute();
$result2 = $stmt2->fetchAll();
}while ($row_rsWorksMenu = $stmt2->fetchAll());
但没有任何反应.
更新2
我试试这段代码:
<?php do { ?>
<li><span><?php echo $result2->year; ?></span>
<ul>
<?php
$titulos = explode(",", $result2->titulos);
$links = explode(",", $result2->links);
foreach(array_combine($links, $titulos) as $link => $titulo){
?>
<li><span><a href="works.php?id=<?php echo $link; ?>"><?php echo $titulo; ?></a></span></li>
<?php } ?>
</ul>
</li>
<?php }while($result2 = $stmt2->fetch()); ?>
我的DOM显示正确的< li>数.但没有价值观.为什么?
最佳答案 最简单的方法是这样的:
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
PDO查询方法返回一个PDOStatement,您可以直接迭代.