简体   繁体   中英

Undefined variable in PHP when referencing MySQL element

Edit: I solved the problem! It was an issue unrelated to the code that I posted - I had an exit command in the script - but all of your advice still helped in other ways.

I'm trying to automatically send an e-mail to a user when they fill out their picks on a sports website. The early part of the script works: Their picks are correctly inserted or updated in the database. The script breaks when I try to pull the user's e-mail address from a table in the MySQL database and use it to send them a message. But what is very strange about this bug is that it doesn't result in any error messages, and for some reason prevents certain echo statements from running while allowing others.

Here's the relevant code:

...

      //set variable for the userID, grabbed from the session array
      $userID = $_SESSION['identifier'];

...

      //write query to get user's e-mail from the database
      $getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";

      //execute query
      $result = $db->query($getEmail);

      //check if query failed
      try
      {
        if (!$result)
        {
          throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
        }
      }
      catch (customexception $e)
      {
        include 'error.html';
        echo $e;
        $db->close();
        include 'footer.php';
        exit;
      }

      //get the info from the row
      $row = $result->fetch_assoc();

      //check if function ran, catch exception if it failed
      try
      {
        if ($row === false)
        {
          throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
        }
      }
      catch (customexception $e)
      {
        include 'error.html';
        echo $e;
        $db->close();
        include 'footer.php';
        exit;
      }

      //set e-mail variable
      $email = $row['email'];

      //set up e-mail information to send a record of their picks to the user
      $toAddress = "$email";

      $subject = "Your Picks";

      $fromAddress = "From: picks@mysite.com";

      //take the info the user submitted, format it for the e-mail, and assign to variable $mailContent
      //the $winner1, $spread1, etc. variables are defined earlier in the function, and were successfully submitted into the database
      $mailContent =  "You picked $winner1 to win by $spread1 points, $winner2 to win by $spread2 points, $winner3 to win by $spread3 points, $winner4 to win by $spread4 points, and $winner5 to win by $spread5 points. \n".
                      "You can change your picks at any time before 1:00pm EST, February 27, 2011. Just go back to the form on the game page and enter your new picks. Good luck!";

      //use wordwrap to limit lines of $mailContent to 70 characters
      $mailContent = wordwrap($mailContent, 70);

      //send the e-mail
      $isMailed = mail($toAddress, $subject, $mailContent, $fromAddress);

      //debug: check if mail failed
      if (!$isMailed)
      {
        echo "Mail failed.";
      }

      //debug: echo $email to see if there's anything in there
      echo "<p>E-mail: $email</p>";

      //debug: echo $toAddress to see if there's anything in there
      echo "<p>To address: $toAddress</p>";

      //if everything succeeded, write reply and close database
      echo $reply;
      $db->close();
    ?>

Just to be clear, $userID is set correctly, because their picks enter the database like they're supposed to. None of the exceptions listed in the code come up, meaning the query seems to have run successfully. I checked the query again by copying it from the PHP code and running it directly on the MySQL database. When it ran directly, it found the correct e-mail address for every userID value I entered.

But the mail never gets delivered, and when I try to echo the $email and $toAddress variables to see if they're empty:

      //debug: echo $email to see if there's anything in there
      echo "<p>E-mail: $email</p>";

      //debug: echo $toAddress to see if there's anything in there
      echo "<p>To address: $toAddress</p>";

...nothing shows up. Not even an error message. And that doesn't necessarily mean that the variables are empty: Not even the labels are echoed.

I also tried the code with my personal e-mail hardcoded instead of $toAddress, and no mail was sent. So the mail function isn't working.

I should also note that the script still successfully echoes $reply (which is a string defined much earlier) at the end.

What's really strange is that the login script for my website uses an almost identical piece of code and works perfectly:

            $getuserID = "SELECT `userID` FROM `useraccounts` WHERE `u_name` = '".$login."' AND `p_word` = SHA1('".$password."')";

            $result = $db->query($getuserID);

            //check if query ran, catch exception if it failed
            try
            {
              if ($result === false)
              {
                throw new customexception("Some kind of database problem occurred when trying to find your user ID.");
              }
            }
            catch (customexception $e)
            {
              include 'error.html';
              echo $e;
              $db->close();
              include 'footer.php';
              exit;
            }

            //get the info from the row
            $row = $result->fetch_assoc();

            //check if function ran, catch exception if it failed
            try
            {
              if ($row === false)
              {
                throw new customexception("Some kind of database problem occurred when trying to get info from your user record in the database.");
              }
            }
            catch (customexception $e)
            {
              include 'error.html';
              echo $e;
              $db->close();
              include 'footer.php';
              exit;
            }

            //set userID variable
            $userID = $row['userID'];

            //assign the session identifier and include successfullogin.html if all is well
            $_SESSION['identifier'] = $userID;

And I used to have the signup script send me an e-mail every time I got a new user, so I know that mail() works in general with my hosting provider:

        //set up static e-mail information
        $toAddress = "myemail@mysite.com";

        $subject = "Advance Sign-Up";

        $mailContent = "Name: $firstName $lastName \n".
                       "Username: $username \n".
                       "Password: $password \n".
                       "E-mail: $email \n".
                       "Country: $country \n".
                       "State: $state \n".
                       "City: $city \n".
                       "ZIP: $zip \n";

        $fromAddress = "From: $email";

...

        mail($toAddress, $subject, $mailContent, $fromAddress);

This bug is completely mystifying to me. I wish I had some sort of error message to work with, at least. Can anyone see what's wrong?

It should be a comment but for the sake of formatting.
Your way of error handling is quite unusual.
If you really want to use exceptions, it should be done different way: one try block and multiple throws:

  try
  {
    $getEmail = "SELECT `email` FROM `useraccounts` WHERE `userID` = '".$userID."'";
    $result = $db->query($getEmail);
    if (!$result)
    {
      throw new customexception("Some kind of database problem occurred when trying to find your e-mail address.");
    }
    $row = $result->fetch_assoc();
    if ($row === false)
    {
      throw new customexception("Some kind of database problem occurred when trying to get your e-mail address from your user record in the database.");
    }
    $email = $row['email'];
    $toAddress = "$email";
    $subject = "Your Picks";
    $fromAddress = "From: picks@mysite.com";
    $mailContent =  "yadda yadda yadda";
    $mailContent = wordwrap($mailContent, 70);

    mail($toAddress, $subject, $mailContent, $fromAddress);

  }
  catch (customexception $e)
  {
    include 'error.html';
    echo $e;
    $db->close();
    include 'footer.php';
    exit;
  }
?>

Are you positive the database variables have contents? I use echo (or print) to quickly make sure the variables aren't empty. Are you positive your email code works? Try it with set values (such as your own personal e-mail) to make sure it works.

忽略这些通知的最好方法是确保变量存在或在普通PHP中使用isset(),如果!isset()抛出异常/错误并正确处理它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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