[英]Insert query not working with MySQL
I don't know if wrote something wrong in the query, or if it's a logic error. 我不知道查询中是否写错了,还是逻辑错误。 The problem is on the second to last line. 问题在倒数第二行。
<?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')");
?>
EDIT: userId and visits are both set to INT in the database. 编辑:userId和访问都在数据库中都设置为INT。
Change: 更改:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");
to: 至:
$q1 = mysql_query("SELECT * FROM visitors WHERE userId=$userId");
Delete the single quotes around $userId
in your SQL queries (since it's an INT). 删除SQL查询中$userId
周围的单引号(因为它是INT)。 It should be like this: 应该是这样的:
mysql_query("UPDATE visitors SET visits='$visits',`unique`='no' WHERE userId=$userId");
and: 和:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES($userId,'1','yes')");
You should add error handling to your sql queries, but the problem (after the correction indicated by @DanielLisik) is the use of a reserved word : unique
. 您应该在SQL查询中添加错误处理,但是问题(在@DanielLisik指示更正之后)是使用保留字 : unique
。
Change your query to: 将查询更改为:
mysql_query("INSERT INTO visitors(userId,visits,`unique`) VALUES('$userId','1','yes')");
You should also consider changing to PDO or mysqli as the mysql_*
functions are deprecated. 由于不建议使用mysql_*
函数,您还应该考虑更改为PDO或mysqli。
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') ");
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.