PHP:使用fetchall()显示表数据 [英] PHP: Displaying table data using fetchall()
问题描述
PHP/MySQL快速问题:
Quick PHP/MySQL question:
我试图将MySQL数据库表中的数据显示为HTML表,由于某种原因,我的代码使每条数据的输出加倍.
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.
这是我的代码:
$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
&NBSP;&NBSP;&NBSP;&NBSP; 1&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; 1&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP ; 用户名 名字&nspsp ; Last Name
1 1 User Name User Name First Name First Name Last Name Last Name
等等.您明白了.为什么会这样呢?顺便说一句,如果我通过参考row []下标0-3手动添加列信息,则所有内容都会正确显示;只有当我使用嵌套的foreach语句时,数据才会重复.
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.
推荐答案
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);
这篇关于PHP:使用fetchall()显示表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!