简体   繁体   中英

UPDATE table record instead of adding a new record MySQL

Ok .. Here is the thing. I want to list users logged on and change their status when logged out. This works perfect. I created a table for that called tblaudit_users. The existing users I SELECT from a tbl_users table.

What I want, is that if an user already exists in the tblaudit_users table it will UPDATE the LastTimeSeen time with NOW(). But instead of updating that record, it creates a new record. This way the table will grow and grow and I want to avoid that. The code I use for this looks like:

+++++++++++++++++++

$ipaddress = $_SERVER['REMOTE_ADDR'];

if(isset($_SESSION['id'])){

    $userId = $_SESSION['id'];
    $username = $_SESSION['username'];
    $achternaam = $_SESSION['achternaam'];
    $district = $_SESSION['district'];
    $gemeente = $_SESSION['gemeente'];

    $query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' AND active = '1' LIMIT 1");
    $query->execute();

    foreach($query->fetchAll(PDO::FETCH_OBJ) as $value){
        $duplicate = $value->username;  
    }

    if($duplicate != 1){

        $insert = $db->prepare("
                    INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
                    VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
                    ");
        $insert->execute();

    } elseif($duplicate = 1){

        $update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE username = '{$username}'");
        $update->execute();

    } else {
        header('Location: index.php');
        die();
    }
}

I am lost and searched many websites/pages to solve this so hopefully someone here can help me? Thanks in advance !!

UPDATE:

I've tried the below with no result.

+++++

$insert = $db->prepare("
                    INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
                    VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
                    ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
                    ");
        $insert->execute();

Ok. I altered my query and code a little:

$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' LIMIT 1");
$query->execute();

if($query){

    $insert = $db->prepare("
                INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
                VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
                ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
                ");
    $insert->execute();

} else {
    header('Location: index.php');
    die();
}

}

I also added a UNIQUE key called pid (primary id). Still not working.

Base on http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html , don't use 'set' in update syntax

example from the page:

INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;

Several issues:

  • You test on $query , but that is your statement object, which also will be valid even if you have no records returned from the select statement;
  • There can be issues accessing a second prepared statement before making sure the previous one is closed or at least has all its records fetched;
  • There is a syntax error in the insert statement ( set should not be there);
  • For the insert ... on duplicate key update to work, the values you provide must include the unique key;
  • SQL injection vulnerability;
  • Unnecessary split of select and insert : this can be done in one statement

You can write your test using num_rows() . To get a correct count call store_result() . Also it is good practice to close a statement before issuing the next one:

$query = $db->prepare("SELECT * FROM tblaudit_users 
                       WHERE username = '{$username}' LIMIT 1");
$query->execute();
$query->store_result();
if($query->num_rows()){
     $query->close();
     // etc...

However, this whole query is unnecessary when you do insert ... on duplicate key update : there is no need to first check with a select whether that user actually exists. That is all done by the insert ... on duplicate key update statement.

Error in INSERT

The syntax for ON DUPLICATE KEY UPDATE should not have the word SET following it.

Prevent SQL Injection

Although you use prepared statements (good!), you still inject strings into your SQL statements (bad!). One of the advantages of prepared statements is that you can use arguments to your query without actually injecting strings into the SQL string, using bind_param() :

$insert = $db->prepare("
    INSERT INTO tblaudit_users (user_id, username, achternaam, district, 
                                gemeente, ipaddress, LastTimeSeen, status)
    VALUES (?, ?, ?, ?, ?, ?, NOW(), '1')
    ON DUPLICATE KEY UPDATE LastTimeSeen = NOW(), status = '1'
    ");
$insert->bind_param("ssssss", $userId, $username, $achternaam, 
                              $district, $gemeente, $ipaddress);
$insert->execute();

This way you avoid SQL injection .

Make sure that user_id has a unique constraint in the tblaudit_users . It does not help to have another (auto_increment) field as primary key. It must be one of the fields you are inserting values for.

The above code no longer uses $query . You don't need it.

I found the issue

if(isset($_SESSION['id'])){

    $userId = $_SESSION['id'];
    $username = $_SESSION['username'];
    $achternaam = $_SESSION['achternaam'];
    $district = $_SESSION['district'];
    $gemeente = $_SESSION['gemeente'];

    $query = $db->prepare("SELECT * FROM tblaudit_users WHERE user_id = '{$userId}' LIMIT 1");
    $query->execute();

    if($query->rowcount()<1){

      $insert = $db->prepare("
                  INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
                  VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
                  ");
      $insert->execute();

    } elseif($query->rowcount()>0) {

        $update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE user_id = '{$userId}'");
        $update->execute(); 

    } else {
        header('Location: index.php');
        die();
    }
}

Instead of using $username in my query, I choose $userId and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM