dpmir1988 2011-09-17 20:16
浏览 29
已采纳

从数组中获取数据 - PHP [关闭]

Okay, I'm kinda stuck on really silly problem, but still can't figure out.

I'm having an array from database with mysql_fetch_array. So far I have only 1 record in the table and after print_r(....) I have this:

Array (
   [0] => 1 
   [customer_id] => 1 
   [1] => Test Client 
   [customer_name] => Test Client 
   [2] => 
   [customer_image] => 
   [3] => Test Address 
   [customer_address] => Test Address 
   [4] => 2272723 
   [customer_phone] => 2272723
)

I'm trying to make a foreach() {...} from where I'll get customer_id and customer_name

and somehow I can't make correct foreach to get them and I'm getting some hilarious results...

any ideas?

=================

$sql = "SELECT * FROM customers";
$result_set = mysql_query($sql, $this->connection);
$records = mysql_fetch_array($result_set);

function generateSelect($recordName, $label, $default) {
        $records = parent::selectTableRecord($recordName);
      $html = "<label for=\"".$recordName."\">". $label ."</label>";
      $html .= "<select name=\"". $recordName ."\" id=\"". $recordName ."\">";
      $html .= "<option value=\"\">". $default ."</option>";
          while ($record = mysql_fetch_assoc($records)) {
            $html .= "<option value=\"".$record['customer_id']."\">".$record['customer_name']."</option>";
          }
      $html .= "</select>";
      return $html; 
    }

and somewhere on other page I'm echoing this function:

<?php echo Project::generateSelect('customer', 'client', '--'); ?>

here's what I have

  • 写回答

6条回答 默认 最新

  • doupeng5320 2011-09-17 21:06
    关注

    the easiest way would be to use this code :

    $result = mysql_query("SELECT * FROM customer");
    while($posts = mysql_fetch_array($result)){
    echo $posts['customer_name'];
    }
    

    Updated answer to reflect the exact vars used in the question

    $sql = "SELECT * FROM customers";
    $result_set = mysql_query($sql, $this->connection);
    while($records = mysql_fetch_array($result_set)){
       echo $records['customer_name'];
    }
    

    now #customer_name can be replaced by ANY field name you have in that table to get that data.

    and if you wanted to use foreach to have $i as a number to keep track of the number of results, then you can create $i = 0; outside the while() and at the end before closing it, just add $i++.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错