Citra45Abadi
Citra45Abadi

Reputation: 207

how to save php variable value after defining it, keeping the last value without reverting the value back to empty?

so I want to make a notification with AJAX call, that checks the sum of rows in database, then compare it the amount from before.

when the AJAX access the php file, first it will check if $old_db is already defined or not, if not then define it.

then it will run the query(not using prepared statement yet because this still experimental to me) to check, num_row query and the store the value into $new_db.

after that it will compare the value and goes on.....

then finally it will assign $new_db value to $old_db

if(!(isset($old_db)) && empty($old_db)){
$old_db = "";
}

$sql = $con->query("SELECT * FROM produk");
$new_db = $sql->num_rows;

if($new_db > $old_db){
    echo "ada";

    echo "<br>".$old_db;
 }

 $old_db= $new_db;

now the problem whenever I run the php file, it never echoed the value of $old_db even though I already assign a value to it at the bottom of the script

I guess everytime I run the script the value got assigned as "" or null again? so how do I prevent that and keep the last value?

I'm thinking about storing it into Cookie....

after thinking about it if I only want to use it as notification then using Session is enough. thank you guys

Upvotes: 0

Views: 277

Answers (1)

Rahul
Rahul

Reputation: 2474

session_start();
$_SESSION['old_db'] = $old_db;
if(!(isset($_SESSION['old_db']) && empty($_SESSION['old_db'])){
$_SESSION['old_db'] = "";
}

$sql = $con->query("SELECT * FROM produk");
$new_db = $sql->num_rows;

if($new_db > $_SESSION['old_db']){
    echo "ada";

    echo "<br>".$_SESSION['old_db'];
 }

 $_SESSION['old_db']= $new_db;

Upvotes: 2

Related Questions