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

时间:2013-09-28 21:59:35

标签: php mysql sql

我正在尝试为我的论坛创建一个函数,它会将我的用户的“帖子”属性增加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''

3 个答案:

答案 0 :(得分:1)

你无法以"toto ".$var+1的方式连接,你必须用括号"toto ".($var+1)

包围

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

错误在于构建查询。

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

我会建议您创建这样的查询提示:

  • “update table set field = value”; //你可以直接写这个值
  • “update table set field =”。 $值; // easy
  • “update table set field =”。 ($一个+ $ b)中; // ...
  • “update table set field = {$ value}”; //你可以添加带花括号的变量
  • “update table set field = {$ va [3]}”; //更无比的方式
  • “更新表格设置字段= {$ a-> b}”; //一个对象字段