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 } ?>
CodePudding user response:
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
$msg
is 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 } ?>
CodePudding user response:
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 } ?>