in the code below, if I echo the variable the condition will work if I don’t echo the variable the condition will not work!
what is the error?
the code:
$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 } ?>
edited code: even this does not work unless echo!
$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 } ?>
>Solution :
There are few problems in the code:
-
Call
session_start();before using $_SESSION. -
$_SESSION['$msg']can be undefined and can trigger notice. You should check if the key exists withisset($_SESSION['$msg']). -
Session key
$msgis a bit strange. You don’t need the$for session keys. -
If you want to check for not
null, use strict comparison!==.
<?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 } ?>