insert 检查 mysql,检查MySQL是否已存在数据;如果不存在,则检查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.

I send array from javascript to PHP file using $.ajax type POST.

Do I need additional 'SELECT' query to check if values already exist?

PHP File(Works, inserts values):

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 . "
" . $conn->error;

}

$conn->close();

?>

解决方案

Use the ON DUPLICATE KEY UPDATE feature. 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:

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)

$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

2 Rows - Update

Take a look at $conn->affected_rows after the query.

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. The update is done in the database, even if it is the same value. Unfortunately there is no 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值