我的PHP SQL查询抛出错误,即使它在SQL控制台中有效

I'm trying to create a function for my forum that will increment my user's "Posts" attribute by 1. For whatever reason, the following PHP does not work.

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
"
    . "FROM users
"
    . "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;
}

I honestly don't see what I'm doing wrong, because the SQL works fine. If I use UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames' in the console, it works with no errors. Help is much appriciated. Also, here is the error it is throwing at me:

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''

Look at your errors, your syntax is off

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

You can not concatenate that way "toto ".$var+1, you have to surround with brackets "toto ".($var+1)

In your case, this is declaration of var $incrementPostsQuery which fails

The error is in the building of your query.

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

I'll suggest you some tips to create query like this:

  • "update table set field = value"; // you can write the value directly
  • "update table set field = ". $value; // easy
  • "update table set field = ". ($a+$b); // ...
  • "update table set field = {$value}"; // you can add a variable with curly braces
  • "update table set field = {$va[3]}"; // more compless way
  • "update table set field = {$a->b}"; // an object field