PHP - Undefined variable

后端 未结 9 746
星月不相逢
星月不相逢 2021-01-26 05:29

I\'m doing some exercises from Beginners PHP & MySQL by Mr. Tucker.

On his example everything works fine, but on my PC there is an error:

相关标签:
9条回答
  • 2021-01-26 05:46
    while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC)) {
      $passwordRetrieved = $row['password'];
    }
    

    this is the only place where a value may be assigned to the variable $passwordRetrieved.
    If there is no record in the result set the body of the while-loop is never executed and therefore no value ever is assigned to $passwordRetrieved and therefore $passwordRetrieved does not exist/is undefined at line 39 -> Notice: Undefined variable: passwordRetrieved in C:\wamp\www\loginForm.php on line 39.

    0 讨论(0)
  • 2021-01-26 05:48

    You should define $passwordRetrieved before using it. This notice does not affect it at all.

    To avoid this, define it:

    $thisScriptName = "loginForm.php";
    
    $passwordRetrieved;
    
    0 讨论(0)
  • 2021-01-26 05:49

    That's because your query returned nothing and your

    while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC)) {

    didn't fill

    $passwordRetrieved

    You can disable E_NOTICE notices because it's not something that would hurt

    Or add

    $passwordRetrieved = "";
    

    before your

    while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC)) {
    
    0 讨论(0)
  • 2021-01-26 05:51

    Do a check using mysql_num_rows($result) to make sure you actually got something.

    0 讨论(0)
  • 2021-01-26 05:52

    You are trying to access the variable $passwordRetrieved when it has not yet been given a value. The access is done here:

    echo "passwordRetrieved = ".$passwordRetrieved."<br />";
    

    The variable would be set just above:

    while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC)) {
        $passwordRetrieved = $row['password'];  // VARIABLE SET HERE
    }
    

    The important thing is that the variable only gets set if the query returns a matching row (i.e., on a successful login). If the login is not valid, the variable is not set.

    To check if a variable is set without getting a notice, you would use either isset or empty (there are subtle differences, but as a rule of thumb you can use either most of the time). Your code actually already does this just below:

    // Checking if $passwordRetrieved has been set using empty()
    if (!empty($passwordRetrieved) AND ($password == $passwordRetrieved)) {
    
    0 讨论(0)
  • 2021-01-26 05:53

    You simply use an undefined variable. If your while loop doesn't work your variable steel is undefined, so you obtain an error :)

    0 讨论(0)
提交回复
热议问题