我正在尝试调整此代码,以便如果结果已经存在于数据库中,那么更新它而不是插入?
有人可以告诉我如何做到这一点。我是mysql和php的新手。
<?php
require_once('includes/session.php');
require_once('includes/functions.php');
require('includes/_config/connection.php');
session_start();
confirm_logged_in();
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
if (!isset($_GET['to']))
exit('No user specified.');
$user_id = $_GET['to'];
$result = mysql_query("SELECT * FROM ptb_likes WHERE liked_id ='".$user_to_id."' ");
mysql_query("INSERT INTO ptb_likes (user_id, liked_id) VALUES (".$_SESSION['user_id'].", ".$user_to_id.")");
if($result)
{
mysql_query("UPDATE ptb_likes SET user_id_has_liked='1' WHERE user_id=".$_SESSION['user_id']."")
or die(mysql_error());
mysql_query("UPDATE ptb_likes SET likes='1' WHERE liked_id=\"$profile_id\"")
or die(mysql_error());
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>
答案 0 :(得分:1)
您应该尝试使用一个MySQL语句。
ON DUPLICATE KEY UPDATE
在此处查看更多内容:http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html