我开发了一个使用Javascript的游戏,当用户完成游戏时,我必须将他的记录保存在数据库中。在这里,您可以看到代码:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
当我有一个新用户(我的“else”中的部分)时,代码正常工作,因为我的数据库中有一个新行。
当用户名已经存在于列表中时,表示此播放器已经发送了他的记录,因此我必须更新该表。顺便说一句,我无法编辑已经发送记录的玩家的记录。
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
看起来这是错误的,我无法理解。我是PHP和MySQL的新手。
你有什么建议吗?
答案 0 :(得分:3)
$temp
声明中UPDATE
周围的引号丢失了:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
但是,最好使用带参数的预准备语句,而不是在查询中插入字符串。
答案 1 :(得分:1)
逃避您的用户输入!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
确保将mysqli_connect()粘贴在
之上$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
在之前发现 UPDATE查询,你应该好好去 - 显然,你需要编辑它以匹配你的表格设置