我的系统让用户输入一个分数,然后通过此php将其添加到数据库中。仅在(当前)已经插入值的情况下才会更新-是否有办法使用此语法在重复项上插入插入更新,从而允许根据SESSION ID更新分数?
<?php
include("php/functions.php");
include('connections/conn.php');
$userID = $_SESSION["userID"];
//echo "all good here";
$newsselfesteemscore = mysqli_real_escape_string($conn, $_POST['selfesteemscore']);
/**$insertquery1 = "UPDATE selfesteemscore SET selestscore = '$newsselfesteemscore' , UserID = '$userID' ";**/
$insertquery1 = "UPDATE selfesteemscore SET selestscore = '$newsselfesteemscore' WHERE UserID = '$userID' ";
$result1 = mysqli_query($conn, $insertquery1) or die(mysqli_error($conn));
mysqli_close($conn);
?>
尝试以下
$newsselfesteemscore = mysqli_real_escape_string($conn, $_POST['selfesteemscore']);
$insertquery1 = "INSERT INTO selfesteemscore(selestscore, UserID) VALUES('$newsselfesteemscore', '$userID')"
. " ON DUPLICATE KEY UPDATE selfesteemscore SET selestscore = '$newsselfesteemscore' WHERE UserID = '$userID' ";
var_dump(mysqli_error($conn));
$result1 = mysqli_query($conn, $insertquery1) or die(mysqli_error($conn));
mysqli_close($conn);
?>
删除WHERE组件后出现的错误
string(0) "" You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET selestscore = '17' , UserID = '25'' at line 1
$insertquery1 = "INSERT INTO selfesteemscore(selestscore, UserID) VALUES('$newsselfesteemscore', '$userID')"
. " ON DUPLICATE KEY UPDATE selfesteemscore(selestscore, UserID) VALUES ('$newsselfesteemscore' , UserID = '$userID') ";
var_dump(mysqli_error($conn));
$result1 = mysqli_query($conn, $insertquery1) or die(mysqli_error($conn));
mysqli_close($conn);
?>
string(0) "" You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(selestscore, UserID) VALUES ('17' , UserID = '25')' at line 1
答案 0 :(得分:0)
The documentation为您提供INSERT .. ON DUPLICATE KEY UPDATE的语法。您的查询应如下所示:
$insertquery1 = "INSERT INTO selfesteemscore(selestscore, UserID) VALUES('$newsselfesteemscore', '$userID')"
. " ON DUPLICATE KEY UPDATE selestscore = '$newsselfesteemscore', UserID = '$userID' ";
但是,如果userID是唯一键,则不要更新它:
$insertquery1 = "INSERT INTO selfesteemscore(selestscore, UserID) VALUES('$newsselfesteemscore', '$userID')"
. " ON DUPLICATE KEY UPDATE selestscore = '$newsselfesteemscore' ";