Issue with fetching query

S.M Talha

Am trying to show a message if alert field is hidden and then updating that field so the message could not be shown again. Values are updating in db but the message is still being displayed can anyone help me finding out whats the issue.

<?php 
$alrt="hidden";
$checkalert=mysql_query("SELECT * FROM user_shift_test WHERE userid='$_SESSION[userid]' AND alert='$alrt' ");
if(!empty($checkalert)){ 
$updatealert=mysql_query("UPDATE user_shift_test SET alert='showed' WHERE userid='$_SESSION[userid]' ");
?>
<div class="alert" style="margin:10px;">
    Your shift is swapped.
</div><?php } ?>
trincot

There are several issues with your code:

  • You use deprecated mysql_ functions: these have not been maintained during the last 3 years and don't exist in PHP 7.xx. You should move to mysqli_ or PDO;
  • You inject strings inside your SQL statements. This could make you vulnerable to SQL injection. Use prepared statements instead;
  • The test !empty($checkalert) will always be true, even if the result set is empty. It is a query object. This is the reason why the message keeps being shown (BTW: not showed);
  • The get-and-set operation can better be done in one SQL operation, which will give you better performance. After the conditional update you can check if a record was updated, and if so, show the message;

Here is code for which you will first need to move to mysqli_ functions (also for the connection):

<?php
// Perform update only if value is hidden
$stmt = mysqli_prepare($con,
    "UPDATE user_shift_test
     SET    alert = 'shown' 
     WHERE  userid = ?
     AND    coalesce(alert, 'hidden') = 'hidden' ");
if ($stmt) {
    // pass session variable as argument
    mysqli_stmt_bind_param($stmt, "s", $_SESSION['userid']);
    mysqli_stmt_execute($stmt);
    // check if any update was performed
    if (mysqli_stmt_affected_rows($stmt)) {
?>
        <div class="alert" style="margin:10px;">
            Your shift is swapped.
        </div>
<?php 
    }
}
?>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related