简体   繁体   中英

Better way to check if row exist update else insert new record

what is the best way to write the query if row exist update else insert new record? I was trying the rubbish code as listed below:

<?php
for ($i = 0; $i < ($_POST['count']); $i++) {
    $form_details_subquestion_id = $_POST['form_details_subquestion_id'][$i];
    $form_details_section_id = $_POST['form_details_section_id'][$i];
    $mark = $_POST['mark'][$i];
    $remark = $_POST['remark'][$i];

    $result = $db->query("
        SELECT * 
        FROM audit_section_markrecord 
        WHERE 
          form_details_subquestion_id = $form_details_subquestion_id AND 
          audit_section_no = $audit_no
    ");
    if ($result->num_rows == 1) {
        $query2 = "
            UPDATE audit_section_markrecord 
            SET 
                mark = '$mark', 
                dateofmodify = '$date' 
            WHERE 
              form_details_subquestion_id = '$form_details_subquestion_id' AND 
              audit_section_no = '$audit_no'
        ";
        $result2 = $db->query($query2);

        $query3 = "
            INSERT INTO markrecord_update_details (
                audit_section_no,
                form_details_subquestion_id, 
                form_details_section_id, 
                mark,
                userlog,
                ipaddress
            ) VALUES (
                '$audit_no', 
                '$form_details_subquestion_id', 
                '$form_details_section_id', 
                '$mark', 
                '$user_staff', 
                '$ip'
            )
        ";
        $result3 = $db->query($query3);
    } else if ($result->num_rows == 0) {
        $query4 = "
            INSERT INTO audit_section_markrecord (
                audit_section_no,
                form_details_subquestion_id, 
                form_details_section_id, 
                mark
            ) VALUES (
                '$audit_no', 
                '$form_details_subquestion_id', 
                '$form_details_section_id', 
                '$mark'
            ) 
        ";
        $result4 = $db->query($query4);
    } else {
        echo "<script>alert('Error. Please contact IT support.')</script>";
        echo "<script language='javascript'>window.location.href='index.php'</script>";
    }
}

The above code is writing inside for loop. I try to get if the form_details_subquestion_id AND audit_no is exist then update old records and insert to markrecord_update_details;else insert new records.

I don't know how to use the most easier to write the code. I just try to learn from this journey.

Best way is insert on duplicate key update .

Explanation for first query.

/* execute this directly in MySQL to add unique key constraint*/
ALTER TABLE audit_section_markrecord
ADD UNIQUE(form_details_subquestion_id, audit_section_no);

/* this query is for calling from php */
INSERT INTO audit_section_markrecord
SET
  /* try to insert value */
  mark = '$mark', 
  dateofmodify = '$date',
  form_details_subquestion_id = '$form_details_subquestion_id',
  audit_section_no = '$audit_no'

/* if constraint check fails, i.e. */
/* there is a row with this form_details_subquestion_id and audit_section_no */
/* then just update mark and dateofmodify */
ON DUPLICATE KEY UPDATE
  mark = '$mark', 
  dateofmodify = '$date';

PS Escape you data to prevent sql-injection !

P.S2. To check it works, run 2 queries in MySQL:

INSERT INTO audit_section_markrecord
SET
  mark = 'good', 
  dateofmodify = '2015-11-10',
  form_details_subquestion_id = 10,
  audit_section_no = 23;

INSERT INTO audit_section_markrecord
SET
  mark = 'good', 
  dateofmodify = '2015-11-10',
  form_details_subquestion_id = 10,
  audit_section_no = 23
ON DUPLICATE KEY UPDATE
  mark = 'excellent', 
  dateofmodify = '2015-11-26';

Row should have mark=excellent and dateofmodify=2015-11-26.

P.S3. If it's inserting duplicate rows, there was a problem with adding the unique key. Take a look at SHOW CREATE TABLE audit_section_markrecord. (Thanks Barmar ).

Another way is to use a REPLACE statement. It works just like an INSERT statement, but when it tries to insert the record, if a record with the same keys exists then deletes the old record and inserts the new one. Since you are not updating based on previous values, this might be easier to work.

The user will need DELETE rights so this works.

Example:

$query4 = "REPLACE INTO `audit_section_markrecord` (audit_section_no,form_details_subquestion_id, form_details_section_id, mark) VALUES 
    ('$audit_no', '$form_details_subquestion_id', '$form_details_section_id', '$mark') ";

@Andrew, seems I'v understood your needs.

You want to update markrecord_update_details only if audit_section_markrecord was updated (not inserted).

You check for update needed by combination of two columns: form_details_subquestion_id and audit_section_no .

Seems your code is working fine. Use it, don't complicate things.

I suggest you to postpone leaning "easier way" to do work. Add data escaping to prevent sql-injection and relax.

PS When you will be ready, google "mysql triggers on update", "unique key" and "on duplicate key update" (my prev example has some foundation for it).

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