Jump to content

[SOLVED] n00b question about while loops and variables


Recommended Posts

Hi All,

 

I'm a fresh-faced PHP baby who has been using ColdFusion for the past several years because my work required it.  Now I'm free and learning PHP for my future projects.

 

I'm sure this question is covered in the forums, but I couldn't find it.

 

Is there a way to access query results WITHOUT using a while or other loop?  The query I have will only return one result, so the loop is unecessary, and I need the data at various points through the rest of the page.

 

In ColdFusion, I could do this by using the variable #queryname.fieldname#.  Is there a PHP equivalent?

 

I tried using the while loop to set variables I could access later:

 

while ($row = mysql_fetch_assoc($result)) {

 

$variable = $row['variable'];

}

 

But I can't access the $variable once the loop has ended.

 

I know this is a stupid question, but I would appreciate the help.

 

Thanks.

I think you can also do

 

 

<?php
// Your query on top of the page
$query = mysql_query("SELECT * FROM table");


  do{

   $row['field_1'];


   }while($row = mysql_fetch_array($query));


  do{

  
   $row['field_2'];


   }while($row = mysql_fetch_array($query));


   $field_1 = mysql_fetch_assoc($query);

   echo $field_1['field_1'];


?>

Is there only one row from the query?  You should be able to access the variables anywhere on the page outside of the while loop, unless that while loop is inside a function and you're trying to access the variable outside of the function.  If there's only one row resulting from the query you could just do this:

 

<?php
$row = mysql_fetch_assoc($result);
   extract($row); // now each field resulting from the query will be it's own variable.
   echo $variable; // Assuming there's a field in your database called "variable"

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.