PHP: Displaying table data using fetchall()

爷,独闯天下 提交于 2019-12-22 14:14:09

问题


Quick PHP/MySQL question:

I'm trying to display the data from a MySQL database table as an HTML table, and for some reason my code doubling the output of each piece of data.

This is my code:

$rowarray = $statement->fetchall();
print "<tr>\n";  
foreach ($rowarray as $row) {
    foreach ($row as $col) {
        print "\t<td>$col</td>\n";
    }
    print "</tr>\n";
}  

My results look something similar to this:

User ID | User Name | First Name | Last Name

    1              1            User Name   User Name     First Name     First Name     Last Name     Last Name

Etc etc. You get the idea. Why this is happening? By the way, if I manually add the column information by referring to row[] subscripts 0-3, everything is displayed properly; it's only when I use the nested foreach statements that the data is duplicated.


回答1:


You are getting both a numeric and a name-indexed value back from PDO fetchall. To get just the numeric index:

$rowarray = $statement->fetchall(PDO::FETCH_NUM);


来源:https://stackoverflow.com/questions/8393034/php-displaying-table-data-using-fetchall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!