我不知道在查询中是否写错了,或者是否是逻辑错误。问题出现在倒数第二行。
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
$num = mysql_num_rows($q1);
if($num==1){
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1)){
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(userId,visits,unique) VALUES('$userId','1','yes')");
?>
编辑:userId和访问都在数据库中设置为INT。
答案 0 :(得分:0)
变化:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
为:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId=$userId");
删除SQL查询中$userId
周围的单引号(因为它是INT)。它应该是这样的:
mysql_query("UPDATE visitors SET visits='$visits',`unique`='no' WHERE userId=$userId");
和
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES($userId,'1','yes')");
答案 1 :(得分:0)
您应该为sql查询添加错误处理,但问题(在@DanielLisik指示的更正之后)是使用reserved word:unique
。
将您的查询更改为:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES('$userId','1','yes')");
您还应该考虑更改为PDO或mysqli,因为mysql_*
函数已弃用。
答案 2 :(得分:0)
i think first error in in variable name using in $ql and second is $num==1 if in visitors table multiple record of thats user then this condition will be wrong ($num==1) so i think replace it with this ($num>0)
<?php
include "connectdb.php";
$userId = mysql_real_escape_string($_GET["userId"]);
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='$userId' ");
$num = mysql_num_rows($q1);
if($num>0)
{
//user exists, update visits and unique values
$visits = 0;
while($row=mysql_fetch_array($q1))
{
$visits = $row["visits"] + 1;
echo $row["visits"] + 1;
}
mysql_query("UPDATE visitors SET visits='$visits',unique='no' WHERE userId='$userId'");
die();
}
//if there is no current visitor
mysql_query("INSERT INTO visitors(`userId`,`visits`,`unique`) VALUES ('$userId','1','yes') ");
?>