我有这个函数读取数组的内容,并将数据从mysql数据库输出到表中。但是,当数组中存在重复时,它只会列出该信息一次。在下面的代码中,它只给我三个表行,1,100和140.它跳过了第二个实例1.我如何修复它以将数据输出到表中而不管是否有重复项?
$con = mysql_connect('localhost', 'root', 'password');
$table = "cwr";
$player1pod1 = array(1, 1, 100, 140);
function generatelistplayer1 ($player1pod1, $con, $table){
$sql = "SELECT * FROM $table WHERE id IN (".implode(',',$player1pod1).")";
$myData = mysql_query($sql, $con);
echo "<table border='1' cellpadding='2'> ";
while($row = mysql_fetch_array( $myData )) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['cardname'] . '</td>';
echo '<td>' . $row['rarity'] . '</td>';
}
echo "</table>";
该表的所需输出为:
我得到了:
答案 0 :(得分:1)
它只会给你3行,因为它只会给你独特的行。如果您想要实际重复,可以使用UNION
查询。
"SELECT * FROM $table WHERE id = 1 UNION ALL SELECT * FROM $table WHERE id IN (".implode(',',$player1pod1).")";
如果要使用该数组,可以创建一个循环:
$query = [];
foreach($player1pod1 as $pod) {
$query[] = "SELECT * FROM $table WHERE id = $pod";
}
$sql = implode(" UNION ALL ",$query);
答案 1 :(得分:0)
首先获取所有结果(进入数组,键是id),然后根据原始列表显示每个结果。
答案 2 :(得分:0)
您可以在循环中根据需要多次打印结果。
注意它不是查询的循环。对db的查询只会进行一次,我不推荐一个多次查询或多次查询相同数据的解决方案。
如果顺序不重要,即数组(1,100,1,140)=良好=数组(1,1,100,140),我们可以使用array_count_values($ player1pod1)并打印每个结果需要:
$con = mysql_connect('localhost', 'root', 'password');
$table = "cwr";
$player1pod1 = array(1, 1, 100, 140);
function generatelistplayer1 ($player1pod1, $con, $table)
{
$counts = array_count_values($player1pod1);
$sql = "SELECT * FROM $table WHERE id IN (" . implode(',', $player1pod1) . ")";
$myData = mysql_query($sql, $con);
echo "<table border='1' cellpadding='2'> ";
while ($row = mysql_fetch_array($myData)) {
for ($i=0;$i<count($counts[$row['id']]);$i++) {
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['cardname'] . '</td>';
echo '<td>' . $row['rarity'] . '</td>';
}
}
echo "</table>";
}
如果订单很重要,我们可以先从数据库sql收集数据,然后逐个打印,用&#34; print_rows&#34;功能在我的例子中。在这个解决方案中,我们不需要计算值,但我们使用一些RAM来保存sql结果:
function generatelistplayer1 ($player1pod1, $con, $table)
{
$sql = "SELECT * FROM $table WHERE id IN (" . implode(',', $player1pod1) . ")";
$myData = mysql_query($sql, $con);
//extract data
$sql_data = array();
while ($row = mysql_fetch_array($myData)) {
$sql_data[$row['id']] = array( 'cardname'=> $row['cardname'],'rarity'=> $row['rarity']);
}
//print data
print_rows($player1pod1,$sql_data);
}
function print_rows($player1pod1, $mysql_data)
{
echo "<table border='1' cellpadding='2'> ";
for($i=0;$i<count($player1pod1);$i++) {
echo "<tr>";
echo '<td>' . $player1pod1[$i] . '</td>';
echo '<td>' . $mysql_data[$player1pod1[$i]['cardname']] . '</td>';
echo '<td>' . $mysql_data[$player1pod1[$i]['rarity']] . '</td>';
}
echo "</table>";
}