在mysql表中,我有3个字段。user_to、user_from和id。变量都是正确的,并且应该插入正确的数据。
当点击一个名为'poke‘的按钮时,它应该插入cookie,该cookie存储了谁做了这件事,以及谁被戳了。它似乎没有插入,我被卡住了:(
$cookie = $_SESSION['user_login'];
//Poke code
if (@$_POST['poke']) {
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$username' && user_from='$added_by'");
$num_poke_found = mysql_num_rows($check_if_poked);
if ($num_poke_found == 1) {
echo "Come on! Give the guy a chance!";
}
else
if ($username == $cookie) {
echo "You cannot Jab yourself.";
}
else
{ $poke_user = mysql_query("INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')") or trigger_error(mysql_error());
echo "$username has been jabbed.";
}
}发布于 2012-11-16 07:27:38
您在MySQL查询中对字段使用了错误的引号。
//your wrong variant
"INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')"
//right variant
"INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$cookie', '$username')"Quotes like‘mean values and quotes like’SQL语法中的字段
发布于 2012-11-16 07:38:24
<?php
if ($_POST['poke']) {
#ref to the current user
$from = $_SESSION['user_login'];
#ref to the (poked user)
$to = $_POST['poked_user_id'];
if($from == $to){
echo "you cant poke yourself!";
}
else{
#ADVICE: USE PDO OR MYSQLI INSTEAD OF MYSQL
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$to' AND user_from='$from'");
if(mysql_num_rows($check_if_poked)){
echo "Come on! Give the guy a chance!";
}
else{
if(mysql_query("INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$from', '$to')")){
echo "$to has been jabbed.";
}
else{
trigger_error(mysql_error());
}
}
}
}
?>发布于 2012-11-16 08:03:29
这一开始只是一个评论--但它太长了,无法适应。
会话和用户名不是一回事--你的帖子非常混乱。
抛开错误的引号不谈(这就是为什么你的代码没有做你期望的事情)……
在mysql表中,我有3个字段。user_to、user_from和id
..。在这种情况下,您不需要检查行是否已经存在,也不需要创建重复的行。设置一个唯一的索引,然后...
if (@$_POST['poke'] && ($_SESSION['user_login']!===$username)) {
$qry = "INSERT INTO `pokes` (`user_from`, `user_to`)
VALUES (".mysql_real_escape_string($_SESSION['user_login'])
.", '" . mysql_real_escape_string($username) . "')"
if (mysql_query($qry)){
echo "$username has been jabbed.";
} else if (stristr(mysql_error(), 'duplicate')) {
echo "Come on! Give the guy a chance!";
} else {
echo "It's all gone Pete Tong!";
}
} else if ($_SESSION['user_login']!===$username) {
echo "You cannot Jab yourself.";
}虽然PHP处理的工作量大致相同,但DB的工作负载要小得多。这段代码还可以防止一些SQL注入攻击,并具有错误处理功能。我假设已经在其他地方创建了$username,并且您没有启用register_globals。
https://stackoverflow.com/questions/13407975
复制相似问题