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

mrfwxfqh  于 2023-01-01  发布在  PHP
关注(0)|答案(1)|浏览(142)
    • 此问题在此处已有答案**:

(29个答案)
2天前关闭。
调用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>
atmip9wb

atmip9wb1#

在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>

相关问题