2014-12-07 50 views
-3

我有一个用PHP编写的迷你游戏。我想为它建立一个高分区。但我无法正确回应数据。我的数据库如何从Mysql正确回应数据

+--------+----------+----------------------------------+---------------------+------+------+ 
| UserID | Username | Password       | EmailAddress  | win | lost | 
+--------+----------+----------------------------------+---------------------+------+------+ 
|  1 | utku  | e10adc3949ba59abbe56e057f20f883e | [email protected]  | 3 | 6 | 
|  2 | utku2 | e10adc3949ba59abbe56e057f20f883e | [email protected]  | 5 | 15 | 
|  3 | utku3 | e10adc3949ba59abbe56e057f20f883e | sad     | 0 | 0 | 
+--------+----------+----------------------------------+---------------------+------+------+ 

我试图用这个代码来呼应他们(我发现它在另一个问题的题目)

<?php include "base.php"; ?> 

<? 
$query="SELECT Username,win,lost FROM users ORDER BY win"; 
$results = mysql_query($query); 

while ($row = mysql_fetch_array($results)) { 
    echo '<tr>'; 
    foreach($row as $field) { 
     echo '<td>' . htmlspecialchars($field) . '</td>'; 
    } 
    echo '</tr><br>'; 
} 
?> 

它打印DATAS这样

utku3utku30000 
utkuutku3366 
utku2utku2551515 

但我想以这种形式打印它们

Username Win Lost 
utku2  5 15 
utku  3 6 
utku3  0 0 

我该怎么做。我是新的PHP

+1

的DOC告诉你['数组mysql_fetch_array($资源结果[摘要$ result_type的= MYSQL_BOTH])'](HTTP:// PHP。 net/manual/en/function.mysql-fetch-array.php)和'MYSQL_BOTH':'通过使用MYSQL_BOTH(默认),你将得到一个包含关联和数字索引的数组。'这就是为什么你得到每一列两次。 – 2014-12-07 18:18:53

回答

1

您不应该打印tr, td没有table标记。你也没有加入th。可以试试这个

echo '<table><tr><th>User Name</th><th>Win</th><th>Lost</th></tr>'; 
while ($row = mysql_fetch_array($results)) { 
    echo '<tr><td>'.$row['Username'].'</td><td>'.$row['win'].'</td><td>'.$row['lost'].'</td></tr>'; 
} 
echo '</table>'; 
+0

我认为最主要的问题就是一切都得到了echo'd两次 – 2014-12-07 18:20:17

+0

它仍然打印值的两倍 – JayGatsby 2014-12-07 18:22:11

+0

更新了我的帖子@JayGatsby。希望现在它会帮助你! – MH2K9 2014-12-07 18:25:32

-2

你不需要foreach循环,因为while循环做递归iteraction,这就是为什么你有两次的结果:

while ($row = mysql_fetch_array($results)) { 
    echo '<tr>'; 
     echo '<td>' . htmlspecialchars($field['Username']) . '</td>'; 
     echo '<td>' . htmlspecialchars($field['win']) . '</td>'; 
     echo '<td>' . htmlspecialchars($field['lost']) . '</td>'; 
    echo '</tr><br>'; 
} 
+0

不用,那跟它没什么关系。 while循环遍历每行,而foreach遍历每个字段 – 2014-12-07 18:22:23

2

你不应该使用mysql_,因为它是过时,将在未来版本的PHP中被删除。 您应该切换到mysqli_PDO。 (Overview of the MySQL PHP drivers > Choosing an API

您的问题是:
array mysql_fetch_array (resource $result [, int $result_type = MYSQL_BOTH ])

MYSQL_BOTH:[...]By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.[...]

这就是为什么你每列的两倍。

速战速决将使用MYSQL_NUMMYSQL_ASSOC

mysql_fetch_array($results, MYSQL_ASSOC) 
相关问题