简体   繁体   English

PHP 代码插入/更新/删除 SQL 数据库中的条目

[英]PHP code to Insert / Update / Delete entries in a SQL database

I have two databases, one very big (5 GB) and a smaller one which is updated with a PHP running as a cron job to extract the necessary data from the big database.我有两个数据库,一个非常大(5 GB),一个较小的数据库更新为 PHP 作为 cron 作业运行以从大数据库中提取必要的数据。

I have so far been able to extract the data from the big database and insert it in the small one if the row doesn't already exist.到目前为止,我已经能够从大数据库中提取数据并将其插入到小数据库中(如果该行尚不存在)。

This is how a database row looks like:这是数据库行的样子:

123456 TeamA-TeamB 1.14 4.30 7.60
(id, eventname, odds1, oddsX, odds2)

The PHP needs to a) check whether the row exists, b1) add it if it doesn't exist, b2) if it does exist check do the values odds1, oddsX and odds2 differ, c) if they do, update the values. PHP 需要 a) 检查该行是否存在,b1) 如果它不存在则添加它,b2) 如果它存在检查值 odds1、oddsX 和 odds2 是否不同,c) 如果它们不同,更新值。

This is the code which does a) and b1):这是执行 a) 和 b1) 的代码:

$SQL_INSERT="INSERT IGNORE INTO oddsnavi_baby.calc (id, eventname, odds1, oddsX, odds2) VALUES ('$eventid', '$eventname', '$odds1', '$oddsX', '$odds2')";
mysql_db_query($database_baby, $SQL_INSERT) or die("Failed Query of " . $SQL_INSERT);

How do I change this part to get the row updated if the existing values of either odds1, oddsX or odds2 are different than the ones intended to be written to the database?如果 odds1、oddsX 或 odds2 的现有值与打算写入数据库的值不同,我如何更改此部分以更新行? It would also be fine if the row would be updated if any value is different, as the first two won't change anyway.如果任何值不同,也可以更新该行,因为前两个无论如何都不会改变。

$SQL_INSERT="INSERT IGNORE INTO oddsnavi_baby.calc (id, eventname, odds1, oddsX, odds2) VALUES ('$eventid', '$eventname', '$odds1', '$oddsX', '$odds2')";
$SQL_UPDATE="update oddsnavi_baby.calc set odds1=\"$odds1\",oddsX=\"$oddsX\",odds2=\"$odds2\" where id=\"$eventid\");
$query="select * from oddsnavi_baby.calc where id=\"$eventid\"";
$process=mysql_query($query);
if(mysql_num_rows($process))       
        mysql_db_query($SQL_UPDATE);
else
        mysql_db_query($database_baby, $SQL_INSERT) or die("Failed Query of " . $SQL_INSERT);

here in this case there is a redundancy if there is no change in row data then also it will be updates which would be an overhead.在这种情况下,如果行数据没有变化,则存在冗余,那么它也将是更新,这将是一种开销。 Checking for values could reduce it检查值可以减少它

Try:尝试:

REPLACE INTO 

instead of INSERT IGNORE INTO.而不是 INSERT IGNORE INTO。

Docs here: http://dev.mysql.com/doc/refman/5.0/en/replace.html文档在这里: http://dev.mysql.com/doc/refman/5.0/en/replace.html

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

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