问题:
我一直在查看我的代码,但找不到数组复制数据的原因。数据库中的单个条目具有正确的输出,但是如果有多个条目,它将复制之前的条目以及下一个条目。
我的代码:
global $connection;
//Query database & retrieve results.
$search = $connection->query('SELECT * FROM users WHERE country= "'.$country.'"');
echo '<table><tr><th>Username</th><th>Email</th><th>Country</th></tr>';
while ($result = $search->fetch_assoc())
{
$total[] = $result;
foreach ($total as $rows)
{
echo '<tr>';
echo '<td>'.stripslashes($rows['username']).'</td>';
echo '<td>'.stripslashes($rows['email']).'</td>';
echo '<td>'.stripslashes($rows['country']).'</td>';
echo '</tr>';
}
}
echo '</table>';
输出:
这将返回以下形式 -
Username Email Country
exampleUser1 exampleEmail1@example.com United States
exampleUser1 exampleEmail1@example.com United States
exampleUser2 exampleEmail2@example.com United States
你可以看到第一行是重复的,然后是新的条目,它会继续从这里继续下去。
附加信息:
- 这被放置在函数内部并在提交 $_POST['country'] 时执行 - $country 只是带有 real_escape_string 的 $_POST['country']。
- $connection 只是脚本中引用的一个新的 mysqli(localhost, user, pass, database) - 它是全局化的,因为它被包装在一个函数中。
如有任何帮助,我们将不胜感激。
最佳答案
<?php
//... Your code
while ($rows = $search->fetch_assoc()) {
$rows = array_map('stripslashes', $rows);
echo '<tr>';
echo '<td>'.$rows['username'].'</td>';
echo '<td>'.$rows['email'].'</td>';
echo '<td>'.$rows['country'].'</td>';
echo '</tr>';
}
//... Your code
如果您需要保存并从函数中返回此行,只需创建数组 $total 并添加 $total[] = $rows;
在 echo '</tr>';
之后
关于php - MYSQLi 多条记录输出重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27374548/