简体   繁体   English

如果ID存在,则更新行,否则插入

[英]Update a row if ID exists else Insert

This is the code of a .php file. 这是一个.php文件的代码。 The column "memberid" has a unique index. 列“ memberid”具有唯一索引。 When a user enters a record with an existing memberid, the record must get updated else a new row is created. 当用户输入具有现有成员ID的记录时,该记录必须得到更新,否则将创建新行。

I also want to show an alert box. 我也想显示一个警报框。 For test purposes I added like the way below, but it is not firing. 出于测试目的,我以如下方式添加,但未触发。 No message is displayed. 没有消息显示。

I also want to know whether it is the right approach to handle insert/update automatically? 我还想知道是否是自动处理插入/更新的正确方法?

<META http-equiv="refresh" content="2; URL=socialprofile.html">
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once("../Lib/dbaccess.php");

    //Retrieve values from Input Form
    $CandidateID = $_POST["inCandidate"];
    $SocialProfile = $_POST["inActivities"];

    $InsertQuery = "INSERT INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";
    $UpdateQuery = "UPDATE candidate_db_social SET socialactivities='".$SocialProfile."', lastupdated=now() WHERE memberid=".$CandidateID;
    try
    {
        $Result = dbaccess::InsertRecord($InsertQuery); 
    }
    catch(exception $ex)
    {
        $Result = dbaccess::InsertRecord($UpdateQuery);
        echo "<script type='text/javascript'>alert('".$ex."');</script>";
    }
?>

See the MySQL REPLACE keyword . 参见MySQL REPLACE关键字 It works exactly like INSERT , but overwrites existing records based on primary key. 它的工作原理与INSERT完全相同,但是会基于主键覆盖现有记录。 Read up on the details though, because it's not exactly equivalent to trying an INSERT, followed by an UPDATE. 请仔细阅读详细信息,因为它并不完全等同于尝试INSERT,然后进行UPDATE。

INSERT ... ON DUPLICATE might be what you need instead. INSERT ... ON DUPLICATE可能正是您需要的。 Situations with triggers or foreign keys come to mind. 想到带有触发器或外键的情况。 Longer syntax however :) 但是语法更长:)

REPLACE INTO candidate_db_social (memberid, socialactivities, lastupdated) VALUES (".$CandidateID.",'".$SocialProfile."',now())";

you can use the INSERT ... ON DUPLICATE KEY UPDATE syntax, as in: 您可以使用INSERT ... ON DUPLICATE KEY UPDATE语法,如下所示:

insert into t values ('a', 'b', 'c') on duplicate key
  update a='a', b='b', c='c'

I usually just check for the existence of a record ID value from either the $_POST or $_GET array (depending on the situation). 我通常只检查$ _POST或$ _GET数组中是否存在记录ID值(取决于情况)。 If a value exists and is numeric, attempt to UPDATE the row with the corresponding ID; 如果值存在并且是数字,请尝试使用相应的ID更新该行;否则,请执行以下操作。 if not perform an INSERT query. 如果不执行INSERT查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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