0

我有一个包含从 mysql 表中查询的数据的数组,我想使用 foreach 在数组中显示特定数据(特定列数据)。

+------+-------+------+-----+
| id   | name  | sex  | age |
+------+-------+------+-----+
|    1 | tom   | m    |  18 |
|    2 | jane  | f    |  32 |
|    4 | Doyle | m    |  25 |
+------+-------+------+-----+

假设数组名称是 $candidates,我需要从 $candidates 显示的只是列“名称”中的名称......

我已经使用 while 循环完美地完成了这项工作,但我不想再次运行数据库查询,因为数据已经存在于数组 $candidates 中

以下是代码:

1. Class function performing the query

       <?php

    class pubCourses {
            function getPubRegCand($org_id, $c_id){
            //fetch the list of registered candidates for this course
            $query_reg_cand = @mysql_query("select * from public_reg_cand where org_id='".$org_id."'");
            $cand = array();
            $cand = @mysql_fetch_assoc($query_reg_cand);

            return $cand;
                    }
          }
        ?>

2. Calling the class function 

    <?php
        $obj = new pubCourses();
        $candidates = array();
        if(isset($_GET['c_id']) && isset($_GET['org_id'])){
            $candidates = $obj->getPubRegCand($_GET['org_id'], $_GET['c_id']);
        }
    ?>

3. Foreach statement to display the candidates names


      <?php

        foreach($candidates as $id=>$cands){
      ?>
     <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td class="bold">Participant&#039;s Name: <?php echo ucwords($cands['name']); ?></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
     </tr>
     <?php
        }
     ?>

上面的 foreach 语句没有显示我需要的“名称”,而是显示第一行的第一个字符,即 1、t、m、1...

请帮我解决这个问题...谢谢

4

2 回答 2

1

Why not do a regular while loop with your query?

$mysqli = new mysqli("localhost", "user", "password", "db_name");
$query = "SELECT name FROM your_table";

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) {
        echo <<<HTML 
<tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td class="bold">Participant&#039;s Name: {$row['name']}</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
</tr>
HTML;
        //echo $row['name'];
    }
}
于 2012-11-26T09:44:12.763 回答
0

因为您要从数据库返回一行...

利用

 while($row=mysql_fetch_array($query_reg_cand)) {
   $cand[] = $row;
 }

代替

$cand = @mysql_fetch_assoc($query_reg_cand);

这应该可以......不需要使用$id=>$cands(除非你想要钥匙)。你可以做..

 foreach($candidates as $cands){...

最后

Use of mysql extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used
于 2012-11-26T10:21:49.160 回答