我正在创建一行“x5产品相关表”并使用MYSQLcode RAND生成RANDOM产品和使用id!='$ id'的异常子句 - 其中id是当前正在查看的现有产品。
但问题是所生成的所有产品图像都是相同的相似产品图像。 任何人都可以对此有所了解吗?
Pic以便更好地参考:
include "MyOnlineStore/storescripts/connect_to_mysql.php";
$sql2 = mysql_query("SELECT * FROM bag WHERE id!='$id'ORDER BY RAND()LIMIT 5");
$productCount2 = mysql_num_rows($sql2); // count the output amount
if ($productCount2 > 0) {
?>
<table border="1">
<tr>
<?php
while ($row2 = mysql_fetch_array($sql2)) {
$idrelated = $row2["id"];
$imagerelated = $row2["image"];
$titlerelated = $row2["title"];
}
} else {
echo "That item does not exist.";
exit();
}
mysql_close();
HTML
<table border="1">
<tr>
<td>
<a href="http://example.net/product.php?id=<?php echo $idrelated; ?>">
<img src="admin/product/uploaded_files/<?php echo $imagerelated; ?>" width="100" height="100" alt="<?php echo $titlerelated; ?>" />
</a>
</td>
<td>
<a href="http://example.net/product.php?id=<?php echo $idrelated; ?>">
<img src="admin/product/uploaded_files/<?php echo $imagerelated; ?>" width="100" height="100" alt="<?php echo $titlerelated; ?>" />
</a>
</td>
<td>
<a href="http://example.net/product.php?id=<?php echo $idrelated; ?>">
<img src="admin/product/uploaded_files/<?php echo $imagerelated; ?>" width="100" height="100" alt="<?php echo $titlerelated; ?>" />
</a>
</td>
<td>
<a href="http://example.net/product.php?id=<?php echo $idrelated; ?>">
<img src="admin/product/uploaded_files/<?php echo $imagerelated; ?>" width="100" height="100" alt="<?php echo $titlerelated; ?>" />
</a>
</td>
<td>
<a href="http://example.net/product.php?id=<?php echo $idrelated; ?>">
<img src="admin/product/uploaded_files/<?php echo $imagerelated; ?>" width="100" height="100" alt="<?php echo $titlerelated; ?>" />
</a>
</td>
</tr>
</table>
答案 0 :(得分:1)
您的代码应该是这样的
include "MyOnlineStore/storescripts/connect_to_mysql.php";
$sql2 = mysql_query("SELECT * FROM bag WHERE id!='$id'ORDER BY RAND()LIMIT 5");
$productCount2 = mysql_num_rows($sql2); // count the output amount
if ($productCount2 > 0) {
?>
<table border="1">
<tr>
<?php
while ($row2 = mysql_fetch_array($sql2)) {
$idrelated = $row2["id"];
$imagerelated = $row2["image"];
$titlerelated = $row2["title"];
?>
<td>
<a href="http://example.net/product.php?id=<?php echo $idrelated; ?>">
<img src="admin/product/uploaded_files/<?php echo $imagerelated; ?>" width="100" height="100" alt="<?php echo $titlerelated; ?>" />
</a>
</td>
<?php
}
?>
</tr>
</table>
答案 1 :(得分:1)
据我所知,您可以从代码中看到以下变量:
$idrelated, $imagerelated, $titlerelated
离开循环后保持不变。因此,在每一行中,您都会引用相同的变量和值。
如果你想继续使用一些数组来保留所有五个值:
<?php
$index = 0;
while (...) {
$relatedA[$index] = ...;
$relatedB[$index] = ...;
$relatedC[$index] = ...;
$index++;
}
?>
...
<?php echo $relatedA[0]; ?>
<?php echo $relatedA[1]; ?>
...
<?php echo $relatedA[4]; ?>
最后你可以再次放入循环以避免冗余代码。
尝试抵制将回声放入第一个获取值的循环的诱惑 - 因为它可能导致难以维护的意大利面条式代码(不幸的是在许多php源中很常见)。