While accessing SQL using php, why enter a variable like '".$q."' instead of just $q or "$q"

StackOverflow https://stackoverflow.com/questions/17891607

  •  04-06-2022
  •  | 
  •  

문제

The statement in question is:

$sql="SELECT * FROM user WHERE id = '".$q."'";

Where q is an integer. Why type it like that when you can just type it like

$sql="SELECT * FROM user WHERE id = $q"; 

because it's an integer, it shouldn't require the quotes right, or even if it did require quotes, why not just one pair. What's the significance of '".$var_name."'?

도움이 되었습니까?

해결책

It doesn't require any '', but in combination with *real_escape_string, to make it effective, you need these single quotes.

Because if the user input would be: 1 OR 1 = 1, then the query is:

SELECT * FROM user WHERE id = 1 OR 1 = 1

what would select the whole table.

But if you use single quotes with *real_escape_string and the user input is 1' OR '1' = '1, then the query would be:

SELECT * FROM user WHERE id = '1\' OR \'1\' = \'1'

what won't select the whole table, but just one id.

tl;dr: It is not needed, but it makes your code safe against sql injection.

다른 팁

First off, the double quotes are there because concatenation is being used; the following two statements are equivalent:

$sql = "SELECT * FROM user WHERE id = '" . $q . "'";
$sql = "SELECT * FROM user WHERE id = '$q'";

That said, integers don't need to be quoted in SQL, so this would be fine:

$sql = "SELECT * FROM user WHERE id = $q";

If $q wasn't sanitized yet and you don't wish to use prepared statements, you could use sprintf() in the following manner:

$sql = sprintf("SELECT * FROM user WHERE id = %d", (int)$q);

In the case of strings I would go for prepared statements or make sure the variable is properly escaped (in case the deprecrated mysql_ functions are still used):

$sql = sprintf("SELECT * FROM user WHERE id = '%s'", mysql_real_escape_string($q));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top