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

why the php condition not work unless i echo the variable?

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:

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

$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:

  1. Call session_start(); before using $_SESSION.

  2. $_SESSION['$msg'] can be undefined and can trigger notice. You should check if the key exists with isset($_SESSION['$msg']).

  3. Session key $msg is a bit strange. You don’t need the $ for session keys.

  4. 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 } ?>
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