Trouble with mysql_fetch_array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
richbis
Forum Newbie
Posts: 1
Joined: Fri Feb 14, 2003 9:17 am

Trouble with mysql_fetch_array

Post by richbis »

I can print the results of an sql query out to a page, however i then want to use one of these results as a variable. I realise that $row[1] for example does not retain the value once it has been printed. How do i print this out and record it as a variable to be used on the next page. This is what i have so far :

mysql_connect("localhost", "supaper", "supaper5");
mysql_select_db("supaper") or die ("Unable to connect");

$result = mysql_query("select * from GRINDS where (grind_name like richard') AND
(stud_uname is not NULL) order by grind_name ");

while($row=mysql_fetch_array($result, MYSQL_BOTH))

if (!empty($row['grind_name']))
{
echo "<tr>\n";
echo "<td ><p><b>Grind ID:</b></p>$row[0]</td>\n";
echo "<td ><p><b>Grind Name:</b></p> $row[1]</td>\n";
echo "<td ><p><b>Grind Description:</b></p> $row[2]</td>\n";
echo "<td ><p><b>Grind Class:</b></p> $row[3]</td>\n";
echo "<td ><p><b>Grind StartDate:</b></p> $row[4]</td>\n";
echo "<td ><p><b>Grind Price:</b></p> $row[5]</td>\n";
echo "<td ><p><b>Student Name:</b><a href =\"../main/Tutor_DisplayStudent_Page.php\"> $row[7]</a></p></td>\n";
echo "</tr>";
}
else
{
echo "No results found";
}
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

It confused me at first that a select query creates an object not an array.

You'll need to declare individual VARs if you have to use them several times. It might be convenient to create an array of the query object, something like this (beware not tested):

Code: Select all

while ($row = mysql_fetch_array..etc) &#123;
       $x = 0;
           foreach ($row as $key => $value) &#123;
           $array&#1111;$x]&#1111;$key] = $value;
           $x++;
       &#125;
&#125;
Or, you could declare them all like this:

Code: Select all

$result = mysql_query("select * from GRINDS where (grind_name like richard') AND 
(stud_uname is not NULL) order by grind_name "); 

$x = 1;
while($row=mysql_fetch_array($result, MYSQL_BOTH)) 
if (!empty($row&#1111;'grind_name'])) &#123;  
    $str = "this" . $x;
    $$str = $row&#1111;0];
    $str = "that" . $x;
    $$str =  $row&#1111;1]; 
   .....other vars......
   $x++;
  ......................
   rest of code
  .......................
&#125; else &#123; 
    echo "No results found"; 
&#125;
That should give you a set of VARs for each (non-empty) result row.

Although I use something similar I haven't tested the exact code above.
Post Reply