我想如果一条记录不存在,我会添加它,否则会更新它……但它不起作用,这段代码有什么问题:
<?php
$user_id=$_POST['user_id'];
$user_email="user_email";
$last_stage=$_POST['last_stage'];
$score=$_POST['score'];
$note=$_POST['note'];
$con=mysqli_connect("localhost","ferfer","Drfrj","ferfw");
$result = mysqli_query($con,"SELECT user_email FROM rating WHERE user_email='".$user_email."'");
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//echo "exist";
mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."' WHERE user_email='".$user_email."'";
mysqli_close($con);
}else{
//echo "does not exist";
mysqli_query($con,"INSERT INTO rating(user_id, user_email, last_stage, score, note)VALUES (".$user_id.",'".$user_email."',".$last_stage.",".$score.",'".$note."') ");
mysqli_close($con);
}
?>
由于MySQL
已经实现了INSERT。。。关于复制密钥更新,如果不存在,基本上INSERT
是一条记录,否则UPDATE
是它。
您需要做的第一件事是在表中添加一个UNIQUE
列。在您的示例中,我看到user_email
是您正在搜索存在的列。如果这不是唯一的,则需要更改UNIQUE
约束的表
ALTER TABLE rating ADD CONSTRAINT tb_uq UNIQUE(user_email)
在实现之后,构建一个这样的查询,
INSERT INTO rating(user_id, user_email, last_stage, score, note)
VALUES($user_id, '$user_email', last_stage, score, '$note')
ON DUPLICATE KEY UPDATE
user_id = $user_id,
last_stage = $last_stage,
score = $score,
note= '$note'
附带说明一下,如果变量的值(s(来自外部,那么查询就容易受到SQL Injection
的攻击。请看下面的文章,了解如何防止它。通过使用PreparedStatements
,您可以摆脱在值周围使用单引号的情况。
- 如何防止PHP中的SQL注入
$user_email="user_email";
应该改为
$user_email=$_POST['user_email'];
和missing(simbol,正如@Yogesh Suthar所说。您还应该考虑对字符串中的字符进行转义,例如使用mysql_real_sescape_string函数。
您忘记了此处的)
mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."'
WHERE user_email='".$user_email."'");
^ // here
更好的方法是使用
REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(@user_id,@user_email,@last_stage,@score,@note) WHERE user_email=@email
还可以使用绑定和准备好的语句,使其更加安全。您的代码非常不安全,因为您既没有也没有转义函数也没有强制转换。
使用PHP绑定的示例$dbh是PDO对象。
$stmt = $dbh->prepare("REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(@user_id,@user_email,@last_stage,@score,@note) WHERE user_email=@email");
$stmt->bindParam('@name', (int)$user_id);
$stmt->bindParam('@user_email', $user_email);
$stmt->bindParam('@last_stage', $last_stage);
$stmt->bindParam('@score', $score);
$stmt->bindParam('@note', $note);
更多关于http://pl1.php.net/pdo
使用绑定,您不必转义字符串,因为它直接进入数据库层,而不必粗略地拼接到SQL语句中。
MySQL REPLACE语句的工作方式与INSERT语句类似,具有附加规则:
如果要插入的记录不存在,MySQL REPLACE将插入一条新记录。如果要插入的记录已经存在,MySQL REPLACE会先删除旧记录,然后插入新记录。
$user_email="user_email";
应为$user_email=$_POST["user_email"];