0

I have two PHP files, index.php and insert.php.

  • index.php - a form and a button to send data
  • insert.php - receives the values of the form to insert them into a database, and it works.

When I redirect to the index.php, it shows a successful message.

I have this code in index.php to show the message:

<?php
   $mensaje=$_GET['mensaje'];
   if($mensaje=="")
      {
      }
   else
      {
         echo "¡Registro exitoso!";
      }
?>

but when I open it the first time, it shows me:

Notice: Undefined index: mensaje in C:\xampp\htdocs\..\index.php on line 41

How could I show the message ONLY after the insert?

Tony
  • 2,658
  • 2
  • 31
  • 46
Veronica20_qro
  • 85
  • 1
  • 1
  • 8

3 Answers3

4

Like this:

$mensaje = isset($_GET['mensaje']) ? $_GET['mensaje'] : "";

That way, $mensaje will never be undefined.


The ternary operator works this way:

$mensaje = if($_GET['mensaje'] exists) then $mensaje = $_GET['mensaje'], else $mensaje = "";

It's like doing:

if(isset($_GET['mensaje'])){
    $mensaje = $_GET['mensaje'];
}
else
    $mensaje = "";
}

For a more accurate information about ternary operators:

http://en.wikipedia.org/wiki/%3F:

For information about function "isset":

http://php.net/manual/en/function.isset.php

1

This happens because your $_GET['mensaje'] not only is empty but doesn't exist at all.
To work this around, replace

$mensaje = $_GET['mensaje'];

by

$mensaje = empty($_GET['mensaje'])? "": $_GET['mensaje'];

Thus you assign an empty string "" if $_GET['mensaje'] is either blank or not set.

Andre Polykanine
  • 3,291
  • 18
  • 28
0

Can $mensaje really be empty (as your if condition implies) or is it simply defined or undefined in $_GET (as your text description implies)? If the latter is the case than your solution is to test for existence, not for content:

<?php
if( isset($_GET['mensaje']) )
{
    echo "¡Registro exitoso!";
}
else
{
}
?>

isset() is a language construct, not a function. This is the reason why it can be used to test for existence of an array index without throwing an "undefined index" notice if the index does not exist.

Hint (just for completeness):
isset() will also return False if the value of an array element is NULL. But this is irrelevant in the case of $_GET, as it always and exclusively contains string values.

Jpsy
  • 20,077
  • 7
  • 118
  • 115