0

mysql テーブルからクエリされたデータを含む配列があり、foreach を使用して配列に特定のデータ (特定の列データ) を表示したいと考えています。

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

配列名が $candidates であると仮定すると、$candidates から表示する必要があるのは、列 'name' の名前だけです....

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 に答える