-2

I got this code below and it shows me just first result of an array. How can it show me all of them?

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

Also, i would like to echo area name and date but when i do select * and echo name and date i got nothing.

Thanks

Brandon
  • 16,382
  • 12
  • 55
  • 88
jak
  • 7
  • 1
  • 5
  • Please read this regarding the MySQL extension - http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php#answer-12860140 – Phil Mar 04 '13 at 02:46
  • possible duplicate of [fetch multiple row output from mysql](http://stackoverflow.com/questions/15055037/fetch-multiple-row-output-from-mysql) – John Conde Mar 04 '13 at 02:47
  • thanks for reply but i still cant get all results from array – jak Mar 04 '13 at 02:57

1 Answers1

0

Your main problem is you keep re-writing the value of $parent; that's why you only get one row's data back. $parent needs to be an array you can add to over rows found.

Also, consider using PHP's PDO instead, it's safer and more object oriented:

$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.
BIT CHEETAH
  • 1,200
  • 1
  • 7
  • 10
  • thanks. now am getting error: Call to a member function rowCount() on a non-object – jak Mar 04 '13 at 11:21