2012-04-26 90 views
-2

当我尝试从特定列下的某个表中查询某些内容时,回显结果显示两个值,一个键值为0,另一个值为该列的键名称。为什么PHP foreach显示查询两次?

我的代码是这样的:

$查询= “选择nepal_posts ID”; $ queryExe = mysql_query($ query,$ connection);

while ($fetched = mysql_fetch_array($queryExe)) { 
    foreach ($fetched as $key => $value) { 
     echo $key."----->".$value." "; 
    } 
} 

和结果是这样的:

0 -----> 9 ID -----> 9 0 - - - - > 10 - - - - 编号> 10

为什么有两次重复?

我该如何编码才能获得正确的结果?

我的数据库表是这样的:

ID - > 9,10题 - >关于我们/嗡奥斯,我们的服务/ VA¥[R Verksamhet 后 - > BLA BLA,BLA BLA

+2

因为mysql_fetch_array默认情况下取得的数值和关联格式 – 2012-04-26 01:35:10

+4

没有人读手册了您的数据:( – Phil 2012-04-26 01:35:33

+4

@Phil#1是新的搜索界面,使用手册,就像谷歌是“德intarwebs” (或Facebook,取决于你的年龄) – deceze 2012-04-26 01:37:08

回答

3

使用mysql_fetch_assoc()而不是mysql_fetch_array()

while ($fetched = mysql_fetch_assoc($queryExe)) { 
    foreach ($fetched as $key => $value) { 
     echo $key."----->".$value." "; 
    } 
} 
+0

谢谢,问题是解决但我想知道究竟发生了什么 – monk 2012-04-26 01:35:23

+3

RTFM没有发生。 :(http://php.net/mysql_fetch_array – Blake 2012-04-26 01:37:44

5

mysql_fetch_array

返回与提取的行相对应的字符串数组,或者如果没有更多行,则返回 FALSE。返回数组的类型取决于 如何定义result_type通过使用MYSQL_BOTH(默认值),您将获得一个包含关联索引和数字索引的数组 。使用MYSQL_ASSOC, 您只能获得关联索引(如mysql_fetch_assoc()作品),使用 MYSQL_NUM,您只能获得数字索引(如mysql_fetch_row()作品)。

http://php.net/mysql_fetch_array

+0

是的,个人喜欢使用'MYSQL_ASSOC'作为我的db类模块使用的默认模式,而不是对'mysql_fetch_assoc()'进行更硬编码的调用。 – zanlok 2012-04-26 01:49:31