-2

我在下面得到了这段代码,它只显示了数组的第一个结果。它如何向我展示所有这些?

$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>";
}

另外,我想回显区域名称和日期,但是当我选择 * 并回显名称和日期时,我什么也没得到。

谢谢

4

1 回答 1

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.
于 2013-03-04T03:29:44.670 回答