我有一个查询来从我的数据库中获取结果。它有效...直到有超过2个结果,然后它才会在添加新结果之前重复一些结果。
我知道这是因为我的查询相当差,任何人都可以建议我吗?
这个想法是
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
$result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos");
while($row = mysqli_fetch_array($result2))
{
echo "<img src=\"" . $row[0] . "\">";
}
}
答案 0 :(得分:1)
mysql_fetch_row返回数字索引而不是列名(所以['default']只是不起作用)...
如果我理解正确的话,我会这样做:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_assoc($result))
{
$answer = $row['photo_'.$row['default']];
echo "<img src=\"" . $answer . "\">";
}
无论如何,这是假设默认值和photo_x在同一行。
答案 1 :(得分:0)
如果您只想获得一张照片的结果,那么您可以像这样使用LIMIT
SELECT $answer FROM tbl_photos LIMIT 1
答案 2 :(得分:0)
首先,两个循环都设置相同的$ row变量。使用2个不同的变量名称,以便结果不会混淆。
第二个问题是你有2个循环,所以每次都会显示所有结果。你需要打破第二个循环。像这样:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
$result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos");
while($row2 = mysqli_fetch_array($result2))
{
echo "<img src=\"" . $row2[0] . "\">";
break;
}
}
或者只使用一个查询,效率会更高:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
echo "<img src=\"" . $row[$answer] . "\">";
}
答案 3 :(得分:0)
您只需要1个查询。
TRY
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$photo = "photo_" .($row['default'];
echo "<img src=\"" . $photo . "\">";
}