为什么在mysql_query(“string”)中使用$ query而不是直接查询字符串?

Could someone please explain to me why the following doesn't work:

mysql_query("DELETE FROM `categories` WHERE `id` = '{$id}'");

Whereas the following does work:

$query = "DELETE FROM `categories` WHERE `id` = '{$id}'";
mysql_query($query);

They both should work exactly the same.

Try this:

mysql_query("DELETE FROM categories WHERE id = '{$id}'");

That always works for me. But putting it in a variable makes it easier to work with sometimes.

There's no difference between the two. Both are vulnerable to SQL injection, as well. You should use prepared statements or mysql_real_escape_string.

There's no functional different between the two, but storing the query in a separate variable makes it easier to debug the statement that's produced.

e.g.

$sql = "...";
$result = mysql_query($sql);
if ($result === FALSE) {
    echo "Query failed: ", $sql, mysql_error();
}

I suspect online examples just started using a separate $query variable, and people copied it without really thinking about it, and then more examples implemented that, and now tons of people do it without necessarily knowing why. C'est la vie.