我通过从数据库获取数据在php中创建最新的产品列表。我想从我的数据库中回复18个最新产品。我正在为每个项目提供外部html,这些项目将针对具有不同数据的所有产品进行回显。以下是获取最新产品的查询
$query = mysql_query("SELECT * FROM devices ORDER BY id DESC LIMIT 3") or die(mysql_error());
while($row=mysql_fetch_array($query))
这是html:
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 nopadding">
<div class="device_box">
<a title="'.$row['name'].'" href="'.$row['link'].'"><img class="img-responsive" alt="'.$row['name'].'" title="'.$row['name'].'" src="'.$row['img'].'" /></a>
<span>
<a title="'.$row['name'].'" href="'.$row['link'].'">'.$row['name'].'</a>
<br /><div class="price_small">'.$row['price'].'</div>
</span>
</div>
</div>
我希望使用foreach循环回显18个产品。我尝试使用foreach但它显示错误。
Warning: Invalid argument supplied for foreach()
任何帮助都会得到满足。感谢。
答案 0 :(得分:0)
试试这个
$sql = "sql query";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_row($result)) {
echo '<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 nopadding">
<div class="device_box">
<a title="'.$row['name'].'" href="'.$row['link'].'"><img class="img-responsive" alt="'.$row['name'].'" title="'.$row['name'].'" src="'.$row['img'].'" /></a>
<span>
<a title="'.$row['name'].'" href="'.$row['link'].'">'.$row['name'].'</a>
<br /><div class="price_small">'.$row['price'].'</div>
</span>
</div>
</div>';
}
答案 1 :(得分:0)
不要将$ row分配给$ data,如$ data [] = $ row。虽然循环可以排序你的问题,不要去foreach。使用此:
$query = mysql_query("SELECT * FROM devices ORDER BY id DESC LIMIT 3") or die(mysql_error());
while($row=mysql_fetch_array($query)){ ?>
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 nopadding">
<div class="device_box">
<a title="<?php echo $row['name'] ?>" href="<?php echo $row['link'] ?>"><img class="img-responsive" alt="<?php echo $row['name'] ?>" title="<?php echo $row['name'] ?>" src="<?php echo $row['img'] ?>" /></a>
<span>
<a title="<?php echo $row['name'] ?>" href="<?php echo $row['link'] ?>"><?php echo $row['name'] ?></a>
<br /><div class="price_small"><?php echo $row['price'] ?></div>
</span>
</div>
</div>
<?php } ?>
答案 2 :(得分:-1)
试试这个
<?
$sql = "YOUR QUERY HERE";
$result = mysql_query($conn, $sql);
//if (mysql_num_rows($result) > 0) {
// output data of each row
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
foreach($data as $key=>$val) { ?>
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 nopadding">
<div class="device_box">
<a title="<?php echo $val['name']; ?>" href="<?php echo $val['link'];?>"><img class="img-responsive" alt="<?php echo $val['name'];?>" title="<?php echo $val['name'];?>" src="<?php echo $val['img'];?>" /></a>
<span>
<a title="<?php echo $val['name'];?>" href="<?php echo $val['link'];?>"><?php echo $val['name'];?></a>
<br /><div class="price_small"><?php echo $val['price'];?></div>
</span>
</div>
</div>';
<? } ?>