如何从 while 循环内部调用变量到循环外部 [duplicate]

How to call a variable from within the while loop to the outside of the loop [duplicate]

提问人:vinz 提问时间:12/29/2022 最后编辑:vinz 更新时间:12/29/2022 访问量:26

问:

在我的 while 循环之外调用变量时出现错误 调用变量的正确方法是什么?

$gettingusername = $_GET['username'];
global $connectionDB;
$sql = "SELECT name, lastname FROM admin WHERE username=:username";
$stmt = $connectionDB->prepare($sql);
$stmt->bindValue(':username', $gettingusername);
$stmt->execute();
$result = $stmt->rowCount();
if($result==1){
    while ($fetch = $stmt->fetch()){
        $existingname = $fetch['name'];
        $existinglastname = $fetch['lastname'];
    }
}

<html>
<?php echo $existingname;?> //OUTPUT UNDEFINED VARIABLE HOW TO FIX IT?
<?php echo $existinglastname;?> //OUTPUT UNDEFINED VARIABLE HOW TO FIX IT?
</html>
php 循环 while-loop

评论


答:

0赞 Danz 12/29/2022 #1

在 while 和 if 之前创建变量

$gettingusername = $_GET['username'];
global $connectionDB;
$sql = "SELECT name, lastname FROM admin WHERE username=:username";
$stmt = $connectionDB->prepare($sql);
$stmt->bindValue(':username', $gettingusername);
$stmt->execute();
$result = $stmt->rowCount();
$existingname = '';
$existinglastname = '';
if($result==1){
  while ($fetch = $stmt->fetch()){
    $existingname = $fetch['name'];
    $existinglastname = $fetch['lastname'];
  }
}

<html>
<?php echo $existingname;?> //OUTPUT UNDEFINED VARIABLE HOW TO FIX IT?
<?php echo $existingname;?> //OUTPUT UNDEFINED VARIABLE HOW TO FIX IT?
</html>