Re: Fwd: Re: [PHP-DB] numeric string to single digit array

From: Date: Wed, 26 Mar 2008 23:33:00 +0000
Subject: Re: Fwd: Re: [PHP-DB] numeric string to single digit array
References: 1  Groups: php.db 
Request: Send a blank email to php-db+get-44820@lists.php.net to get a copy of this message
Richard Dunne wrote:
Using this extract from http://ie.php.net/manual/en/control-structures.foreach.php Amaroq 09-Mar-2008 06:40 Even if an array has only one value, it is still an array and foreach will run it. <?php $arr[] = "I'm an array."; if(is_array($arr)) {
    foreach($arr as $val)
    {
        echo $val;
    }
} ?> The above code outputs: I'm an array. ------------------------------------- So if I use: $query = "Select answer from answers where studentID='A123456789'"; $result = mysql_query($query,$connection) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { foreach($row as $answer) { echo $answer . "\n"; } } I thought I would be able to print out each array element, but I am not getting any output. Has anyone got a better idea?
Instead of using a foreach inside the while loop, just access the array key directly. The name of the key is the name of the column (or alias) from your query. It should be simply: $query = "Select answer from answers where studentID='A123456789'"; $result = mysql_query($query,$connection) or die(mysql_error()); while ($row = mysql_fetch_assoc($result)) { print_r($row); echo "Answer is ", $row['answer'], "\n"; } If a result set has no results (ie your query does not return anything - there are no matching rows), then php won't actually get into the while loop. You can see how many rows are returned by using: $query = "Select answer from answers where studentID='A123456789'"; $result = mysql_query($query,$connection) or die(mysql_error()); $number_of_results = mysql_num_rows($result); Though I suggest only doing this for small result sets - otherwise mysql has to actually process all of the query results which are then stored in memory on the server. -- Postgresql & php tutorials http://www.designmagick.com/

« previous php.db (#44820) next »