回显所有数组结果

时间:2013-03-04 02:45:53

标签: php mysql

我在下面得到了这个代码,它只显示了数组的第一个结果。它怎么能告诉我所有这些?

$res = mysql_query("SELECT clients FROM area ORDER BY date") or die("Error: " . mysql_error());
while($row = mysql_fetch_array($res)){ 
    foreach($row as $value){
        $result = explode(",", $value);

        foreach($result as $newvalue){
            $query="SELECT clients FROM names where names.id='$newvalue'";

            $res2 = mysql_query($query);
            $r = mysql_fetch_array($res2);
            $parent = $r['clients']; 
        }
    }


    // echo part

    echo "<td>" . $parent . "</td>";
}

此外,我想回应区域名称和日期,但是当我选择*并回显姓名和日期时,我什么都没有。

由于

1 个答案:

答案 0 :(得分:0)

你的主要问题是你不断重写$ parent的价值;这就是为什么你只得到一行的数据。 $ parent需要是一个可以添加到已找到的行的数组。

另外,考虑使用PHP的PDO,它更安全,更面向对象:

$database = PDO(/*db_connection_data*/);

$stmt = $database->prepare( "SELECT `clients` FROM `area` ORDER BY `date`" );
$stmt->execute();

$res = $stmt->fetchAll( PDO::FETCH_ASSOC );

if( $stmt->rowCount() > 0 ) { # if results were found

     $parent = array();  # array needs to be initialized or else you keep overwriting it.

     foreach( $res as $value ) {

          $stmt = $database->prepare( "SELECT `clients` FROM `names` WHERE `names.id` = ?" );
          $stmt->bindValue( 1, $value );
          $stmt->execute();

          $res2 = $stmt->fetchAll( PDO::FETCH_ASSOC );

          # use $parent[] to add result as next element of the array 
          if( $res2->rowCount() > 0 ) { $parent[] = $res2[ 'clients' ]; }
          else { $parent[] = ""; }

     }

}

echo "<pre>" . print_r( $parent, 1 ) . "</pre>"; # print the $parent array in a more readable form.