开发者

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


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


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]);


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


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'];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜