benhowdle89
benhowdle89

Reputation: 37464

Store a value from a database into a variable for use outside of a "while" in PHP

This is the relevant bit of my code:

while($row1 = mysql_fetch_array($result1)){
            $pro_no = $row1['project_no'];

So outside of this "WHILE" i want to use $pro_no. How do i go about doing this?

Thanks

EDIT: Thanks, didn't realise i would not need a while loop

Upvotes: 0

Views: 1462

Answers (4)

cristian
cristian

Reputation: 8744

If you have only one row you can do


$row1 = mysql_fetch_array($result1));
$pro_no = $row1['project_no'];

or if you have mamy rows you can accumulate values in an array


$pro_no = array();
while($row1 = mysql_fetch_array($result1)){
   $pro_no[] = $row1['project_no'];
}

At the end of while all the values from column project_no will be in your array

Upvotes: 2

David Powers
David Powers

Reputation: 1664

Since $proj_no will change each time the loop runs, you need to assign the values to an array, and access the array.

while($row1 = mysql_fetch_array($result1)){
    $proj_array[] = $pro_no = $row1['project_no'];

Upvotes: 0

Sondre
Sondre

Reputation: 1898

I'm guessing you're problem is that the value of $pro_no changes for each loop and you only reach the last one after the loop. Save them to an array instead to be able to use all later:

$pro_no[] = $row['project_no'];

Hope I understood the problem correctly

Upvotes: 0

powtac
powtac

Reputation: 41040

After the loop it will be filled with the last value from inside the loop. Therefore it makes sense to set it to a default value to make sure it ran trough the while().

Example:

$pro_no = 'DEFAULT VALUE';
while($row1 = mysql_fetch_array($result1)){
    $pro_no = $row1['project_no'];
}
var_dump($pro_no);


// shorter and faster way of finding the last value:
$row1 = mysql_fetch_array($result1);
rsort($row1);
var_dump($row1[0]);

Upvotes: 0

Related Questions