[英]My PHP SQL query is throwing errors, even though it works in the SQL console
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. 我正在尝试为我的论坛创建一个函数,该函数会将用户的“帖子”属性增加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;
}
I honestly don't see what I'm doing wrong, because the SQL works fine. 老实说,我看不出我在做什么,因为SQL可以正常工作。 If I use
UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames'
in the console, it works with no errors. 如果我在控制台中使用
UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames'
,它可以正常工作。 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''
You can not concatenate that way "toto ".$var+1
, you have to surround with brackets "toto ".($var+1)
您不能以这种方式将
"toto ".$var+1
串联起来,而必须用方括号"toto ".($var+1)
包围起来"toto ".($var+1)
In your case, this is declaration of var $incrementPostsQuery
which fails 在您的情况下,这是var
$incrementPostsQuery
声明,该声明失败
Look at your errors, your syntax is off 查看您的错误,语法已关闭
$getCurrentPosts = "SELECT Posts
FROM users
WHERE Username='$username'";
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: 我会建议您一些技巧来创建这样的查询:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.