插入查询不能与MySQL一起使用

时间:2014-02-13 01:57:38

标签: php mysql sql

我不知道在查询中是否写错了,或者是否是逻辑错误。问题出现在倒数第二行。

<?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。

3 个答案:

答案 0 :(得分:0)

1

变化:

$q1 = mysql_query("SELECT * FROM visitors WHERE userId='userId'");

为:

$q1 = mysql_query("SELECT * FROM visitors WHERE userId=$userId");

2

删除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 wordunique

将您的查询更改为:

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') ");
?>