简体   繁体   English

从while循环外部获取变量

[英]Get variable from the outside of while loop

I'm doing user profile page and this one must show current info.我正在做用户个人资料页面,这个页面必须显示当前信息。 But when I display the page it shows errors like this: Undefined variable: PhoneNumber in C:\\wamp\\www\\Assignment\\userpage.php on line 97但是当我显示页面时,它显示如下错误:未定义变量:PhoneNumber in C:\\wamp\\www\\Assignment\\userpage.php on line 97

I cant find the problem, seems all ok for me.我找不到问题,对我来说似乎一切正常。

<!doctype html>
<html>
<head> 
<?php 
header('Content-type: text/html; charset=utf-8');
$link = mysqli_connect("localhost", "root", "");
if (!$link) {
    die('Could not connect : '.mysql_error());
}
$db = mysqli_select_db($link, 'assignment');
if (!$db) {
    die('Could not select db : '.mysql_error());
}

if ($_SESSION['loggedin'] = true) {
    $query = mysqli_query($link, "SELECT UserID FROM users WHERE       UserID=.\$_SESSION['UserID']");
}
$UserID = $query;
$result = mysqli_query($link, "SELECT * FROM users where UserID='$UserID'");
while ($row = mysqli_fetch_array($result)) {
    global $Lname, $Fname, $PhoneNumber, $Gender, $DOB, $Email;
    $Lname = $row['Lname'];
    $Fname = $row['Fname'];
    $PhoneNumber = $row['PhoneNumber'];
    $Gender = $row['Gender'];
    $DOB = $row['DOB'];
    $Email = $row['Email'];
    echo 'nananananana';
}
?>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Movie Renting</title> 
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body id="wrapper">
<div class="order">   
<h1>Таны бүртгэлийн мэдээлэл:</h1>
<form action = "userpage.php" method = "post">
   <table frame="box" style="width:900px; height:auto">
<tr> 
<td> Овог:</td>
<td> <?php echo $Lname ?></td> </tr>

<tr> 
<td> Нэр:</td>
<td> <?php echo $Fname ?></td> </tr>

<tr> 
 <td> Хэрэглэгчийн нэр:</td>
<td> <?php echo $UserID ?></td> </tr>


<tr> 
<td> E-шуудан:</td>
<td> <?php echo $Email ?> </td> </tr>

<tr> 
<td> Утасны дугаар:</td>
<td> <?php echo $PhoneNumber ?></td> </tr>

<tr> 
<td> Хүйс:</td>
<td> <?php echo $Gender ?></td> </tr>

<tr> 
<td> Төрсөн он сар өдөр: </td>
<td> <?php echo $DOB ?></td> </tr>

<a href = "useredit.php">Өөрийн мэдээллээ засах бол энд дарна уу.</a>
</table>

</form>
</div>
</body>
</html>

The scope of a variable is the context within which it is defined.变量的作用域是定义它的上下文。 For the most part all PHP variables only have a single scope.大多数情况下,所有 PHP 变量都只有一个作用域。 This single scope spans included and required files as well.这个单一的范围也涵盖了包含和必需的文件。

For example:例如:

let us assume in a file, example.php, you have the following:让我们假设在文件 example.php 中,您有以下内容:

<?php

$foo = "Hello World";  // global scope

function hello() {
  echo $foo; // reference to local scope
}

hello();
?>

This script will not produce any output because the echo statement in the function hello() refers to a local version of the $foo variable, and it has not been assigned a value within this scope.此脚本不会产生任何输出,因为函数 hello() 中的 echo 语句引用了 $foo 变量的本地版本,并且尚未在此范围内为其分配值。

Now, if you want to gain access to the already defined or declared global scope variable, $foo, from within the function hello(), then you would need to declare the variable $foo using the global keyword from within the function, such as:现在,如果您想从函数 hello() 中访问已定义或声明的全局范围变量 $foo,则需要在函数内使用global关键字声明变量 $foo,例如:

<?php

$foo = "Hello World";  // global scope

function hello() {
  global $foo;
  echo $foo; // reference to local scope
}

hello();
?>

Now invoking function hello() will produce:现在调用函数 hello() 将产生:

Hello World

While-blocks don't have limited scope within its block, and therefore, same principle do not apply, but having the global keyword define variables inside a while-block at a time when the variables do not exist outside the while block do affect the variables. While 块在其块内没有有限的范围,因此,同样的原则不适用,但是当变量不存在于 while 块之外时,让 global 关键字在 while 块内定义变量确实会影响变量。

So in your while block that you currently have:因此,在您目前拥有的 while 块中:

while ($row = mysqli_fetch_array($result)) {
   global $Lname, $Fname, $PhoneNumber, $Gender, $DOB, $Email;
   $Lname = $row['Lname'];
   $Fname = $row['Fname'];
   $PhoneNumber = $row['PhoneNumber'];
   $Gender = $row['Gender'];
   $DOB = $row['DOB'];
   $Email = $row['Email'];
   echo 'nananananana';
}

Either define the variables $Lname, $Fname, $PhoneNumber, $Gender, $DOB, $Email, in global scope outside the while-block, or place the global variables outside of the while-block scope so you can have access to them, such as:在 while-block 之外的全局范围内定义变量 $Lname、$Fname、$PhoneNumber、$Gender、$DOB、$Email,或者将全局变量放在 while-block 范围之外,以便您可以访问它们, 如:

global $Lname, $Fname, $PhoneNumber, $Gender, $DOB, $Email;
while ($row = mysqli_fetch_array($result)) {
  $Lname = $row['Lname'];
  $Fname = $row['Fname'];
  $PhoneNumber = $row['PhoneNumber'];
  $Gender = $row['Gender'];
  $DOB = $row['DOB'];
  $Email = $row['Email'];
  echo 'nananananana';
}

or, I would do something like this:或者,我会做这样的事情:

$Lname = '', $Fname = '', $PhoneNumber = '', $Gender = '', $DOB = '', $Email = '';
while ($row = mysqli_fetch_array($result)) {
   global $Lname, $Fname, $PhoneNumber, $Gender, $DOB, $Email;
   $Lname = $row['Lname'];
   $Fname = $row['Fname'];
   $PhoneNumber = $row['PhoneNumber'];
   $Gender = $row['Gender'];
   $DOB = $row['DOB'];
   $Email = $row['Email'];
   echo 'nananananana';
}

or even if you will not be calling other files within a file, the use of the global keyword in this case is really unnecessary, you can accomplish this in the following way:或者即使您不会调用文件中的其他文件,在这种情况下使用global关键字确实是不必要的,您可以通过以下方式完成此操作:

$Lname = '', $Fname = '', $PhoneNumber = '', $Gender = '', $DOB = '', $Email = '';
while ($row = mysqli_fetch_array($result)) {
   $Lname = $row['Lname'];
   $Fname = $row['Fname'];
   $PhoneNumber = $row['PhoneNumber'];
   $Gender = $row['Gender'];
   $DOB = $row['DOB'];
   $Email = $row['Email'];
   echo 'nananananana';
}

To think about it from an efficiency point of view, why would you want to invoke the global keyword at every while-loop iterative cycle?从效率的角度考虑,为什么要在每个 while 循环迭代循环中调用 global 关键字? I would just define/declare the variables outside the while-loop, and assignment of values will be added in the while loop as it goes through the iterative process.我只会在 while 循环之外定义/声明变量,并且在循环过程中会在 while 循环中添加值的分配。

Variables scope can get a little tricky, hope this helps out.变量范围可能会有点棘手,希望这会有所帮助。

you no need to use of global keyword.您无需使用 global 关键字。

just declare your variable outside of the while loop.只需在 while 循环之外声明您的变量。

$PhoneNumber= "";

while ($row = mysqli_fetch_array($result)) {
    $Lname = $row['Lname'];
    $Fname = $row['Fname'];
    $PhoneNumber = $row['PhoneNumber'];
    $Gender = $row['Gender'];
    $DOB = $row['DOB'];
    $Email = $row['Email'];
    echo 'nananananana';
}
echo $PhoneNumber; 

Now you can access $PhoneNumber from outside of while loop.现在您可以从 while 循环之外访问 $PhoneNumber。

Thanks.谢谢。

  1. Your "$_SESSION['loggedin'] = true" would return always true because it was an assignemnt, no comparision.您的 "$_SESSION['loggedin'] = true" 将始终返回 true,因为它是一个赋值,没有比较。 !empty() prevents undefined indexes-notices. !empty() 防止未定义的索引通知。
  2. Cast UserId to integer to prevent sql injection (even if it should be a trusted source)将 UserId 强制转换为整数以防止 sql 注入(即使它应该是受信任的来源)
  3. If you want empty variables even if noone is logged in (or not found in database), you have to declare them.如果您想要空变量,即使没有人登录(或未在数据库中找到),您也必须声明它们。
  4. You pass a mysqli result object (what you get from your first mysqli_query) as string parameter, it doesn't work like that你传递一个 mysqli 结果对象(你从你的第一个 mysqli_query 得到的)作为字符串参数,它不能那样工作
  5. while ($row = mysqli_fetch_assoc()) would return the last user, if (..) the first. while ($row = mysqli_fetch_assoc()) 将返回最后一个用户,如果 (..) 第一个。 If it's a primary key (userID suggests this) the result is the same.如果它是主键(userID 建议这样做),结果是相同的。

Here is a corrected code:这是一个更正的代码:

$Lname       = '';
$Fname       = '';
$PhoneNumber = '';
$Gender      = '';
$DOB         = '';
$Email       = '';
if (!empty($_SESSION['loggedin']))
{
    $result = mysqli_query($link,
        "SELECT * FROM users WHERE UserID=" . (int)$_SESSION['UserID']
    );
    if ($row = mysqli_fetch_array($result))
    {
        $Lname       = $row['Lname'];
        $Fname       = $row['Fname'];
        $PhoneNumber = $row['PhoneNumber'];
        $Gender      = $row['Gender'];
        $DOB         = $row['DOB'];
        $Email       = $row['Email'];
    }
}

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

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