我有以下一些代码,它们选择一个表,循环遍历与actor匹配的所有值,并显示该actor的评论。
include("app/config/db.php");
$aid=$actor['id'];
$query = "SELECT * FROM `reviews` WHERE `actor_id` = $aid";
$result = $mysqli->query($query);
$num_results = $result->num_rows;
if( $num_results ){
//loop to show each records
while( $row = $result->fetch_assoc() ){
extract($row);
echo "<span class=\"review-score\">";
echo $row['score']*10;
echo "</span>";
echo " by <strong>";
echo $row['author'];
echo "</strong>";
echo " on <strong>";
echo $row['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $row['body'];
echo "</p>";
echo "</br>";
}
}else{
echo "No records found.";
}
$result->free();
$mysqli->close();
我想转换为使用PDO预处理语句。 这就是我尝试过的。它不显示分配给演员的任何评论。请帮忙
include("app/config/db.php");
$aid=$actor['id'];
$st = DBase::singleton()
->prepare(
'select * ' .
'from `reviews` ' .
'where `actor_id` like :aid ' .
'limit 0,10');
$st->bindParam(':aid', $aid, PDO::PARAM_STR);
if ($st->execute())
{
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
echo "<span class=\"review-score\">";
echo $st['score']*10;
echo "</span>";
echo " by <strong>";
echo $st['author'];
echo "</strong>";
echo " on <strong>";
echo $st['created_at'];
echo "</strong>";
echo "<p class=\"review-body\">";
echo $st['body'];
echo "</p>";
echo "</br>";
}
}
质数据库:单
static public function singleton()
{
if (!is_object(self::$pdo))
{
self::$pdo = new PDO('mysql:dbname=' . self::DATABASE . ';host=' . self::HOST,
self::USERNAME,
self::PASSWORD);
}
return self::$pdo;
}
答案 0 :(得分:3)
您将每行的结果存储在$ row中,但是当您想要显示数据时,不会访问$ row。
while ($row = $st->fetch(PDO::FETCH_OBJ))
{
...
echo $st['score']*10;
回声线应为:
echo $row->score*10;
您还提取对象,但以数组形式访问数据。
这就是我如何被教导写一个while循环..我怎么能这样做?
我的观点是,如果为变量分配连续的行值,那么数据就在该变量中,而不是在遍历行的对象中。你所做的就是这样:
for ($i = 0; $i < $count; $i++) {
echo $count;
}
然而在该示例中,应该执行此操作以在循环中获取连续值:
for ($i = 0; $i < $count; $i++) {
echo $i;
}