en el siguiente código, si hago eco de la variable, la condición funcionará; si no hago eco de la variable, ¡la condición no funcionará!
cual es el error
el código:
$msg=$_SESSION['$msg']; echo $msg; if($msg != null){ ?> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> <script > swal.fire({ icon: "success", title: "success", showConfirmButton: false, timer: 1300 }) </script> <?php } ?>código editado: ¡incluso esto no funciona a menos que se haga eco!
$msg="ss"; if(!empty($msg)){ ?> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> <script > swal.fire({ icon: "success", title: "success", showConfirmButton: false, timer: 1300 }) </script> <?php } ?>Hay algunos problemas en el código:
Llame session_start(); antes de usar $_SESSION.
$_SESSION['$msg'] puede no estar definido y puede generar un aviso. Debe comprobar si la clave existe con isset($_SESSION['$msg']) .
La clave de sesión $msg es un poco extraña. No necesita $ para las claves de sesión.
Si desea verificar que no sea null , use una comparación estricta !== .
<?php session_start(); $msg = isset($_SESSION['$msg']) ? $_SESSION['$msg'] : null; echo $msg; if($msg !== null){ ?> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> <script > swal.fire({ icon: "success", title: "success", showConfirmButton: false, timer: 1300 }) </script> <?php } ?>Firstly, in line number 1 you should pull the session key, so if its a variable it should be $msg=$_SESSION[$msg]; else it should be the key name $msg=$_SESSION['msg']; //msg can be replaced by your key name. You can check directly whether the key exist or not and if it is empty as below: if(isset($_SESSION['msg']) && $_SESSION['msg'] != ''){ ?> <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> <script > swal.fire({ icon: "success", title: "success", showConfirmButton: false, timer: 1300 }) </script> <?php } ?>