简体   繁体   English

如果Record存在UPDATE MySql Table或使用PHP INSERT

[英]If Record exists UPDATE MySql Table or else INSERT using PHP

i have to check if record exists in table forex_rates_new, i need to check for 2 criterias that is it has to compare agency_id and currency_name. 我必须检查表forex_rates_new中是否存在记录,我需要检查2个条件,即它必须比较agency_id和currency_name。 If agency_id and currency_name are same then the system has to UPDATE or else INSERT. 如果agency_id和currency_name相同,则系统必须UPDATE或INSERT。

forex_rates_new
id  agency_id   currency_name    rate
1   1111          aaa            1.898
2   2190          aaa            0.787

That is in the database if agency_id with value 111 occurs and currency_name with USD occurs. 如果出现具有值111的agency_id和具有USD的currency_name,则在数据库中。 Next time if the user enters the same value 111 and currency_name as USD then the record should go in updated mode or else insert. 下次,如果用户输入与USD相同的值111和currency_name,则记录应进入更新模式或插入。 This is my query: 这是我的查询:

INSERT INTO forex_rates_new (`agency_id`,`currency_name`,`rate`,`logo`,`created_at`) 
VALUES('".$agency_id."','".$currency_name."','".$rate."','".$logo."', now())

any help is appreciated 任何帮助表示赞赏

i am giving you simple demonstration here how to achieve that. 我在这里向您简单演示如何实现这一目标。 first you need to do select data.something like this. 首先,您需要选择数据。

"SELECT * FROM request WHERE agency_id='$agency_id' ";

Now check if the data exist make update query 现在检查数据是否存在,进行更新查询

"UPDATE request SET field name='$value' WHERE agency_id='$agency_id'";

otherwise something like this. 否则就是这样

INSERT INTO forex_rates_new (`agency_id`,`currency_name`,`rate`,`logo`,`created_at`) 
VALUES('".$agency_id."','".$currency_name."','".$rate."','".$logo."', now())

Your code should be like this. 您的代码应如下所示。

$qry=mysqli_query($con,"SELECT * FROM request WHERE agency_id='$agency_id' ");
$rowCheck=mysqli_num_rows($qry);
    if ($rowCheck>0) { // if data exist update the data
        $qry=mysqli_query($con,"UPDATE request SET field name='$value' WHERE agency_id='$agency_id'");  
    }
    else{ // insert the data if data is not exist
        $qry=mysqli_query($con,"INSERT INTO request (field name) VALUES('$value')");
    }

Remember given code is open to sql injection attack. 请记住,给定的代码容易受到sql注入攻击。 this is logic only this is not full code.to avoiding sql injection attack use prepared statements. 这只是逻辑,这不是完整的代码。为避免sql注入攻击,请使用准备好的语句。

Check true or false by IF and EXISTS 检查truefalseIFEXISTS

IF ( IF(EXISTS(SELECT `agency_id`,`currency_name` FROM forex_rates_new where `agency_id` = "$agency_id" AND  `currency_name` = "$currency_name"),1,0) ) THEN

BEGIN
    UPDATE forex_rates_new  
    SET
    `rate` = "$rate",
    `logo` = "$logo",
    `created_at` = now();
    WHERE `agency_id` = "$agency_id" AND `currency_name` = "$currency_name"
END;

ELSE

BEGIN
    INSERT INTO forex_rates_new 
    (`agency_id`,`currency_name`,`rate`,`logo`,`created_at`) 
    VALUES
    ("$agency_id","$currency_name","$rate","$logo", now());
END;

END IF;

Here you go! 干得好!

<?php    
        $dupl = mysqli_query($con, "SELECT * FROM forex_rates_new WHERE currency_name='$agency_id'") or die(mysql_error($con));

        $row = mysqli_num_rows($dupl);
        if ($row > 0)
        {
            echo "<script language='javascript'>alert('Exists!!!')</script>";

        $stmt1 = $con->prepare("UPDATE forex_rates_new SET column_name=? WHERE column_name=?");
                        if($stmt1)
                        {
                            $stmt1->bind_param('is', $value, $value);
                            $stmt1->execute();
                        }
                      if($stmt1->affected_rows >0)
                      {
                        echo "<script language='javascript'>alert('Updated Sucessfully!!!')</script>";
                      }
                    else
                    {
                        echo "<script language='javascript'>alert('error!!!')</script>";
                    } 
        }

        $stmt = $con->prepare("INSERT into forex_rates_new VALUES(?,?,?,?, now())
        if($stmt)
        {
            $stmt->bind_param('isis', $currency_name, $agency_id, $rate, $logo);
            $stmt->execute();
        }
        if($stmt->affected_rows >0)
        {
            echo "<script language='javascript'>alert('Inserted Successfully!!!')</script>";
        }
        else{
            echo "<script language='javascript'>alert('An error occurred!!!')</script>";
        }
        } 
        ?>

Above is what you want using mysqli prepared statement. 以上是您要使用mysqli准备好的语句。

i stands for integer s stands for string 我代表整数,代表字符串

You can add a UNIQUE KEY to agency_id , currency_name and than you can use "REPLACE" Syntax -> https://dev.mysql.com/doc/refman/8.0/en/replace.html . 您可以将一个UNIQUE KEY添加到agency_idcurrency_name然后可以使用“ REPLACE”语法-> https://dev.mysql.com/doc/refman/8.0/en/replace.html

No need to select and add condition for Update/Insert statement. 无需为Update / Insert语句选择和添加条件。

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

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