Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – warning generated for variable

I am trying to generate an error message in my HTML if one of these two things are happening, however the appropriate message is displaying the HTML, but I’m also given a warning for having a undefined variable.

How would I fix it with how I am doing it?

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$tweet = "{$_POST['tweet']}";

$errorOne = "Error: Your tweet must be less than 140 characters.";
$errorTwo = "Error: Your tweet must not be blank.";

if(strlen($tweet) > 140){
    $errorOneOutput = $errorOne;
}elseif(empty($tweet)){
    $errorTwoOutput = $errorTwo;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <?= $errorOneOutput ?>
    <?= $errorTwoOutput ?>
</body>
</html>

I have tried using exit() in my PHP block instead of embedded HTML but then that doesn’t generate the HTML. I specifically need the error message to be displayed within the HTML like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Challenge 3</title>
</head>
<body>
    <br />
<b>Warning</b>:  Undefined variable $errorOneOutput in <b>C:\xampp\htdocs\WEBD\Challenges\Challenge 3 - Twitter Challenge\insert.php</b> on line <b>29</b><br />
    Error: Your tweet must not be blank.</body>
</html>

I also know that I can just echo out my errors, but again those would be above the HTML and not within it.

>Solution :

The issue is you’re trying to print a variable you haven’t initialised:

<?= $errorOneOutput ?>
<?= $errorTwoOutput ?>

To initialise these variables, add this to the top of your php file:

$errorOneOutput = "";
$errorTwoOutput = "";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading