Why do some variables need quotes and others don’t? Example when I connect to the DB Variables dont need quotes but when I select or insert into a DB I need quotes.
Example:
//variables
$username="username";
$password="password";
$first=$_POST['first'];
$last=$_POST['last'];
//connect to DB
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to connect to database");
//values assigned
$query = "INSERT INTO guestbook VALUES
('','$first','$last','$email','$web','$comment')";
mysql_query($query);
This is a string literal:
"username". It is a value.This is a variable:
$username. It can hold any value. Think of it as a placeholder.This is a variable inside a string literal:
"foo $username bar". It creates a new value.When creating SQL queries, you simply pass a string to the database, which it will parse according to SQL syntax rules. SQL syntax requires that you put quotes around certain parts. It has nothing to do with PHP variables.
Further, this is a constant:
localhost. You do not have a constant of that name defined, it is actually an error that PHP recovers from by creating the string'localhost'from it on the fly. It is actually an error though.Read about these individual parts of the PHP syntax: http://www.php.net/manual/en/langref.php.
You only need quotes if you are creating a new string, e.g.:
"foo". Variables never need quotes. You may use variables inside a string literal, so its value will get interpolated:"foo $bar baz". But"$foo"is always unnecessary, since it simply creates a new string whose only content is the content of a variable.