PHP MySQL Query doesn't work, but works from t

2019-05-24 13:33发布

Here's my code:

$gid = (int) stripslashes($_POST['id']);
echo $gid;

$db = dbConnect(); $test = $db->query('update games set played = played + 1 where id = "$gid"'); echo $db->error; echo $db->errno; die(); }

It works fine from the terminal, and it correctly prints out $gid, and no errors are returned. Am I missing something really obvious?

标签: php mysql mysqli
4条回答
Summer. ? 凉城
2楼-- · 2019-05-24 14:16

anything in single quotes is not parsed. do id="' . $gid . '"

alternatively wrap the entire thing in double quotes and put single quotes around $gid.

查看更多
Juvenile、少年°
3楼-- · 2019-05-24 14:19

try

$test = $db->query
("
    UPDATE `games` 
    SET
       `played` = (`played` + 1)
    WHERE `id` ='" . $gid . "'
");
查看更多
聊天终结者
4楼-- · 2019-05-24 14:29

You are enclosing the query in single quotes. And in single quotes variable interpolation(also called substitution) does not happen.

Simple example:

$who = 'harry potter';
echo 'hi "$who"'; // prints hi "$who"
echo "hi '$who'"; // prints hi 'harry potter'

Change your code as:

$test = $db->query("update games set played = played + 1 where id = '$gid'");

Also from the line: $gid = (int) stripslashes($_POST['id']); its clear that $gid is an integer and there is not need to enclose it in quotes in your query. So we have:

$test = $db->query("update games set played = played + 1 where id = $gid");
查看更多
Summer. ? 凉城
5楼-- · 2019-05-24 14:30
$test = $db->query("UPDATE `games` SET `played` = `played` + 1 WHERE `id` = '" . $gid . "'");
查看更多
登录 后发表回答