PHP function in SQL statement syntax

I have the following code. I would like the username to take the value of the getUserName function, but I am struggling with the syntax. Can anyone tell me what should be correct?

$query = "SELECT user FROM users_entity WHERE username = getUserName()";

      

+2


a source to share


4 answers


You can use period concatenation:

$query = "SELECT user FROM users_entity WHERE username = '".mysql_real_escape_string(getUserName())."'";

      



Be sure to avoid data!

+9


a source


You cannot inline the result of a function directly into a string. However, you can store the contents of a variable:

$username = mysql_real_escape_string(getUserName());
$query = "SELECT user FROM users_entity WHERE username = '$username'";

      



Or you can concatenate your string like this:

$query = 'SELECT user FROM users_entity WHERE username = \'' . mysql_real_escape_string(getUserName()) . '\'';

      

+2


a source


You cannot interpolate (internally string-replace) PHP function names into strings.

You probably want something like this:

$query = sprintf("SELECT user FROM users_entity WHERE username = '%s'"
    mysql_real_escape_string(getUserName())
);

      

0


a source


$query = "SELECT user FROM users_entity WHERE username = '".getUserName()."'";

      

0


a source







All Articles