简体   繁体   English

将数据库中的值存储到变量中,以便在PHP中的“ while”之外使用

[英]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. 所以在“WHILE”之外我想使用$ 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 或者如果你有mamy行,你可以在数组中累积值


$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 在while末尾, project_no列中的所有值都将在您的数组中

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(). 因此,将其设置为默认值以确保它通过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. 我猜你的问题是每个循环$ pro_no的值都会变化,并且循环后只能到达最后一个。 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. 由于$ proj_no将在每次循环运行时更改,因此您需要将值分配给数组,并访问该数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM