这是我做SQL的第三天,我确信它很小。
我有这个代码。 $ con是我的SQL连接变量。
for ($i = 0; $i < mysqli_num_rows(mysqli_query($con, "SELECT * FROM offers WHERE active='y'")); $i++)
{
echo '<div class="dottedBox">User: '.mysqli_fetch_row(mysqli_query($con, "SELECT poster FROM offers WHERE active='y'"))[$i]."<br>
Has: ".mysqli_fetch_row(mysqli_query($con, "SELECT haveamt FROM offers WHERE active='y'"))[$i]." ".mysqli_fetch_row(mysqli_query($con, "SELECT have FROM offers WHERE active='y'"))[$i].'<br>
Wants: '.mysqli_fetch_row(mysqli_query($con, "SELECT wantamt FROM offers WHERE active='y'"))[$i].' '.mysqli_fetch_row(mysqli_query($con, "SELECT want FROM offers WHERE active='y'"))[$i].'</div><br>';
}
第一项输出正常。但是,每个后续项都会导致以下错误:
Notice: Undefined offset: 1 in /var/www/civ/index.php on line 6
Notice: Undefined offset: 1 in /var/www/civ/index.php on line 7
Notice: Undefined offset: 1 in /var/www/civ/index.php on line 7
Notice: Undefined offset: 1 in /var/www/civ/index.php on line 8
Notice: Undefined offset: 1 in /var/www/civ/index.php on line 8
运行SELECT * FROM offers;
在mysql中返回此内容(我正在使用Debian):
mysql> SELECT * FROM offers;
+----------+-----------+---------+-----------+---------+---------+--------+
| poster | have | haveamt | want | wantamt | offerid | active |
+----------+-----------+---------+-----------+---------+---------+--------+
| minicl55 | gfdsafdsa | 3 | fdsafdsa | 2 | 1 | y |
| minicl55 | jklgdsa | 324 | jfklsdjkl | 4522 | 2 | y |
+----------+-----------+---------+-----------+---------+---------+--------+
我有两个问题:
答案 0 :(得分:2)
您正在查询数据库中的循环中的每个值。您应该只需要查询一次数据库,然后遍历结果以显示它们。
$result = mysqli_query($con, "SELECT * FROM offers WHERE active='y'");
while ($row = mysqli_fetch_assoc($result))
{
echo '<div class="dottedBox">User: '.$row['poster']."<br>
Has: ".$row['haveamt']." ".$row['offers'].'<br>
Wants: '.$row['wantamt'].' '.$row['offers'].'</div><br>';
}