Karl Neumann
Karl Neumann

Reputation: 103

Can someone explain the syntax of this code?

I have the following query in a php file which works fine:

$query = "SELECT `name` FROM users WHERE name='".mysqli_real_escape_string($link,$name)."'";

I got it in a tutorial so I'm trying to wrap my head around the syntax. Specifically this part:

'".mysqli_real_escape_string($link,$name)."'

If the function mysql_real_escape_string() returns a string, why are double quotes needed? Also, I understand in php the . means concatenation so is this code adding to the empty string""?

Please help, I'm really screwed up on this one.

Upvotes: 0

Views: 45

Answers (4)

Faiz Ali
Faiz Ali

Reputation: 15

There is no empty strings in this code. The last "'" is just closing the single quoted string that was opened in name='". In mysql queries, strings must be enclosed in quotes and the here the function returns string which is enclosed in single quotes. This can be clarified like this:

$name = mysqli_real_escape_string($link,$name);
$query = "SELECT `name` FROM users WHERE name='".$name."'";

Suppose if the variable $name = 'Joffery' Then the $query variable will be printed like this

SELECT `name` FROM users WHERE name='Joffery'

Upvotes: 0

bcdan
bcdan

Reputation: 1428

There are two types of quotes in most computer programs, ' and ". You use two of the same type to enclose a string, like 'abc' or "def". However, when you need quotes inside the other quotes, you can put '"'. The syntax does not respond to the quote of different type. The same principle applies in here.

In this case, the line of code can be represented as

`$query = "SELECT `name` FROM users WHERE  name=''";`

but the single quotes needs content in them. That gets added by the concatenation.

Upvotes: 0

gastonmancini
gastonmancini

Reputation: 1102

The single quotes identify strings in the SQL query that you are building.

Your query will result for example in:

 SELECT `name` FROM users WHERE name='John';

(note the quotes surrounding John)

The backticks are used to scape objects names.

Upvotes: 0

tadman
tadman

Reputation: 211600

The double quotes are needed because this is using string concatenation to compose a query. This is a really messy way to do this sort of thing as the mysqli driver has support for placeholders:

$query = "SELECT `name` FROM users WHERE  name=?";

The ? represents where your data will go. You then use the bind_param method to add your $name value in there.

If you're disciplined about using placeholders you won't have to worry about quoting or proper escaping.

Upvotes: 3

Related Questions