The single quotes are delimiters for the SQL statement, and have nothing to do with PHP. They tell MySQL where the value for the field starts, and where it stops.
Consider this:
SELECT * FROM mytable WHERE field=new order by name desc
Should the query restrict where field
= "new order by name desc" or should it restrict where field
= "new" and then order the results by the "name" field in descending order?
The quotes make that explicit:
SELECT * FROM mytable WHERE field='new order by name desc'
Furthermore: this is the reason you should escape your values in MySQL. If a user types ' OR 1 = 1; --
into your username field, and your query for authentication is:
SELECT * FROM users WHERE username = '$_POST['username']' AND password = '$_POST['password']'
You end up with:
SELECT * FROM users WHERE username = '' OR 1 = 1 -- ' AND password = 'asfd'
Which is valid SQL and will select all users in your table (because the input from $_POST['username']
has made the rest of the query commented out. However, if you properly escape values, you end up with:
SELECT * FROM users WHERE username = '\' OR 1 = 1 -- ' AND password = 'asfd'
Which means MySQL will look for a user with username
= \' OR 1 = 1 --
and a matching password. You can escape with a simple mysqli_real_escape_string
, however PDO and parameterized queries are always recommended.
I highly recommend you read through some tutorials on PDO, parameters, and SQL injection before working with a database in any web application. You'll thank yourself later.