简体   繁体   English

PHP Mysql While循环覆盖变量并只显示一个结果

[英]PHP Mysql While loops overwrites a variable and displaying only one result

I have a PHP script to populate drop down menu with results obtained from database the problem I am having is that only the last result is displayed in drop down menu. 我有一个PHP脚本来填充下拉菜单,其中包含从数据库获得的结果我遇到的问题是只有最后一个结果显示在下拉菜单中。 I recon it is because the while loop that gets all the results overwrites the variable that stores a string every time is runs. 我重新调试是因为获取所有结果的while循环会覆盖每次运行时存储字符串的变量。

I have tried to find a solution to fix it but ending up in a dark corner with no solution 我试图找到一个解决方案来解决它,但最终在一个没有解决方案的黑暗角落

Php Code: PHP代码:

$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR  course LIKE '%forex%'";
        $query2 = mysqli_query($link, $sql2);
            $opt = '<select id="Forex" name="Forex">';
            $opt1 = '<option value="">Select Forex Workshop</option>';



                while($result2 = mysqli_fetch_assoc($query2)){
                //I belief the $opt2 variable is overwritten every time the loop runs
                    $opt2 = '<option value="">'.$result2['course'].'</option>';
                    print_r($opt2);
                }
                $opt3 =  '</select>';
                return $opt.$opt1.$opt2.$opt3;  


}       

I might be wrong and the issue might be elswhere in the code but when i print_r($result2) all the correct results are there 我可能是错的,问题可能在代码中的地方但是当我print_r($ result2)所有正确的结果都在那里

Just add a . 只需添加一个.

$opt2 .= '<option value="">'.$result2['course'].'</option>';
      ^

Your variable is reinitializing, it should be concatenated. 你的变量是重新初始化的,应该连接起来。

So, the final code should be: 所以,最终的代码应该是:

$opt2 = '';
while($result2 = mysqli_fetch_assoc($query2)){
                //I belief the $opt2 variable is overwritten every time the loop runs
                    $opt2 = '<option value="">'.$result2['course'].'</option>';
                    print_r($opt2);
                }
                $opt3 =  '</select>';
                return $opt.$opt1.$opt2.$opt3;

Yes, you need to append each value: 是的,您需要附加每个值:

$opt2 .= '<option value="">'.$result2['course'].'</option>';

You should also initialise $opt2 before you start the loop. 您还应该在开始循环之前初始化$ opt2。

$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = "";

您需要将每个值与循环中的现有变量连接起来

**$opt2 .= '<option value="">'.$result2['course'].'</option>';**

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

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