dongqian2021 2013-11-16 01:57
浏览 25
已采纳

PHP foreach行为$ var,行名和行号重复[duplicate]

This question already has an answer here:

I coded a simple function to loop trough and display all variables in the sql table. However foreach $row displays the rows two times, 1 time as a row name and 1 time as a row number.

1 : $row['NAME'] Name form

2 : $row[0]' Number form

PHP :

<?php

include "condetails.php";
$query = "select * from pagedetails";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
  foreach($row as $var => $val) {
    echo "VARNAAM :".$var;
    echo "<br />";
    echo "VALUE".$val;
    echo "<br />";
    echo "<br />";
  }
}

?>

OUTPUT :

VARNAAM :0 VALUE1

VARNAAM :id VALUE1

VARNAAM :1 VALUEdddd

VARNAAM :h1txt VALUEdddd

</div>
  • 写回答

3条回答 默认 最新

  • doukuang1897 2013-11-16 02:00
    关注

    It's displayed twice because mysql_fetch_array() grabs the column name and its number.

    If you want just the column names try using mysql_fetch_assoc(), keep in mind mysql_* functions are depreciated and you should be using PDO / MySQLi :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duandu1915 2013-11-16 02:01
    关注

    mysql_fetch_array returns a mixed array with keys as numbers and as column names. You probably want mysql_fetch_assoc(), which only returns the name keys.

    评论
  • douketangyouzh5219 2013-11-16 02:01
    关注

    From the manual:

    mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

    What you you're really looking for is mysqli_fetch_assoc():

    Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 win10商店接入问题
  • ¥15 java 这种树形框吗
  • ¥40 找同学帮敲Python代码
  • ¥15 MYSQL 订单的商品明细重复计算问题
  • ¥15 微信实时共享位置修改
  • ¥100 TG的session协议号转成直登号号后客户端登录几分钟后自动退出设备
  • ¥50 共模反馈回路的小信号增益
  • ¥15 arduino ssd1306函数与tone函数放歌代码不兼容问题
  • ¥70 0.96版本hbase的row_key里含有双引号,无法deleteall
  • ¥15 诊断性META分析合并效能的检验