繁体   English   中英

我的PHP SQL查询即使在SQL控制台中也可以抛出错误

[英]My PHP SQL query is throwing errors, even though it works in the SQL console

我正在尝试为我的论坛创建一个函数,该函数会将用户的“帖子”属性增加1。无论出于何种原因,以下PHP均不起作用。

function postCountIncrease($username) {
    //get the connection variable
    global $con;
    //change to the users database (this function works correctly)
    sqlconnect_users();
    //get current post number (this is also working)
    $getCurrentPosts = "SELECT Posts\n"
    . "FROM users\n"
    . "WHERE Username='".$username."'";
    $query1 = mysqli_query($con, $getCurrentPosts) or die(mysqli_error($con));
    $currentPosts = mysqli_fetch_array($query1);
    //here is the problematic post.  Assume that $username is a valid value, and that I've already done mysqli_real_escape_string() on it
    $incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
    $query2 = mysqli_query($con, $incrementPostsQuery) or die(mysqli_error($con));
    //return the result
    $result = mysqli_fetch_array($query2);
    return $result;
}

老实说,我看不出我在做什么,因为SQL可以正常工作。 如果我在控制台中使用UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames' ,它可以正常工作。 帮助非常有用。 另外,这是它向我抛出的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 WHERE Username='Lampitosgames''

您不能以这种方式将"toto ".$var+1串联起来,而必须用方括号"toto ".($var+1)包围起来"toto ".($var+1)

在您的情况下,这是var $incrementPostsQuery声明,该声明失败

查看您的错误,语法已关闭

$getCurrentPosts = "SELECT Posts 
                    FROM users 
                    WHERE Username='$username'";

错误在于查询的构建。

$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";

我会建议您一些技巧来创建这样的查询:

  • “更新表设置字段=值”; //您可以直接写入值
  • “更新表集字段=”。 $ value; // 简单
  • “更新表集字段=”。 ($ a + $ b); // ...
  • “更新表集字段= {$ value}”; //您可以添加带有花括号的变量
  • “更新表集字段= {$ va [3]}”; //更无聊的方式
  • “更新表集字段= {$ a-> b}”; //对象字段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM