简体   繁体   English

检查MySQL是否已存在数据;如果不存在,则检查INSERT。 [PHP + jQuery Ajax]

[英]Check MySQL if data already exists, if not, INSERT. [PHP+jQuery Ajax]

I'm having trouble creating php code that would insert values into MySQL database but only if they don't already exist. 我无法创建将值插入MySQL数据库的php代码,但前提是它们不存在。

I send array from javascript to PHP file using $.ajax type POST. 我使用$ .ajax类型POST将数组从JavaScript发送到PHP文件。

Do I need additional 'SELECT' query to check if values already exist? 我是否需要其他“ SELECT”查询来检查值是否已经存在?

PHP File(Works, inserts values): PHP文件(Works,插入值):

<?php
SESSION_START();
include('config.php');
if(isset($_POST['predictedMatches'])&&$_SESSION['userid']){
    $predictedMatches=$_POST['predictedMatches'];
    $userid=$_SESSION['userid'];
}else die("ERROR");
$sql="";
foreach($predictedMatches as $predictedMatch){
    $sql.="INSERT INTO predictions(result,userFK,matchFK,tournamentFK) VALUES('".$predictedMatch['result']."','".$userid."','".$predictedMatch['id']."','".$predictedMatch['tourid']."');";
}
    if($conn->multi_query($sql) === TRUE){
        echo "OK";
    }else{
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
$conn->close();
?>

Use the ON DUPLICATE KEY UPDATE feature. 使用ON DUPLICATE KEY UPDATE功能。 It won't insert, if the primary key exists. 如果主键存在,则不会插入。 But you have to update some value, so use the column which is in no index or in the least indexes () in your case probably result). 但是您必须更新一些值,因此请使用没有索引或索引最少的列()(可能会导致这种情况)。 Your primary key has to be composted out of the three FKs: 您的主键必须由以下三个FK堆肥而成:

ALTER TABLE `predictions` ADD PRIMARY KEY( `userFK`, `matchFK`, `tournamentFK`);

PHP-Code, just the SQL statment (I'm a Java Guy, so i tried my best) PHP代码,仅是SQL语句(我是Java Guy,所以我尽力了)

$sql.="INSERT INTO predictions (result, userFK, matchFK, tournamentFK) "
."VALUES('".$predictedMatch['result'] ."','".$userid."','"
.$predictedMatch['id']."','".$predictedMatch['tourid']."') "
."ON DUPLICATE KEY UPDATE result = result ;";

To know if the query was inserted you have to look at the affected row count: 要知道是否插入了查询,您必须查看受影响的行数:

  • 1 Row - Insert 1行-插入
  • 2 Rows - Update 2行-更新

Take a look at $conn->affected_rows after the query. 查询后看看$conn->affected_rows

Performance 性能

INSERT ... ON DUPLICATE KEY UPDATE is definitively faster than a SELECT and INSERT but it's slower than an INSERT of just the needed datasets. INSERT ... ON DUPLICATE KEY UPDATE绝对比SELECTINSERT快,但比仅需要数据集的INSERT慢。 The update is done in the database, even if it is the same value. 即使是相同的值,更新也会在数据库中完成。 Unfortunately there is no ON DUPLICATE KEY UPDATE INGNORE . 不幸的是,没有 ON DUPLICATE KEY UPDATE INGNORE If you have a lot of inserts, that will result in updates, than it may be better to use a cache, lookup values in an array and compare with the array before inserting. 如果插入很多,将导致更新,这比使用高速缓存,在数组中查找值并在插入之前将其与数组进行比较要好。 Only use the ON DUPLICATE KEY UPDATE as fallback. 仅使用ON DUPLICATE KEY UPDATE作为后备。

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

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