php - 插入查询不适用于 MySQL

标签 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。

最佳答案

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

关于php - 插入查询不适用于 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21743722/

相关文章:

php - 更新 SQL 表 php mysql

php - 如果没有小数部分,则将 float 转换为 int

php - 将表单输入与数据库值进行比较

php - 如何将Silverlight Player加载到浏览器中以使用PHP播放视频

php - PHP 语句中变量的串联

php - 检索与单个记录关联的多个值。 MySQL PHP 代码点火器

android - sqlite3按最大值查询并按第二个因素过滤

sql - pyspark中的过滤器值不相等

php - 如何在 Windows 8.1 上安装 PHP 引擎?

sql - 表格驱动的付款时间表