Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 06-21-2011, 01:56 AM   PM User | #1
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,519
Thanks: 45
Thanked 440 Times in 429 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
TIP: Quotes / Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in..

Many new PHP coders will come across this error and will be a bit confused by what it means so I thought I would supply a quick topic to cover the issue in more detail.

Lets suppose we have the following code:
PHP Code:
$sql "INSERT INTO wall (author, message) VALUES ("' .$author. '", "'. $message. '")"
That is one line of PHP containing an SQL statement. To the experienced eye its defective but to a lot of new PHP programmers this looks fine.

First there seems to be some confusion about the quotation marks so I will go into those here.

Single ' quotes are handled by PHP literally. That means what you see inside the ' marks is exactly what you get. Example:
PHP Code:
$Author 'Joe Bloggs';

print 
'Comment written by $Author'
The above will print like this:
Quote:
Comment written by $Author
This is because the single quotes tell PHP that it should be handled exactly as it is without changing anything.

Double " quotes are where our magic happens. Double quotes tell PHP to examine the string inside it and if there are any variables found, replace them with their values. There is however a trade-off: PHP checks double quoted strings for variables it needs to replace - this uses more CPU cycles. Example:
PHP Code:
//Not good (but it does work):
$Author "Joe Bloggs";

//Better - Uses less CPU (PHP doesn't need to check the string)
$Author 'Joe Bloggs';

print 
"Comment written by $Author"
The above will print like this:
Quote:
Comment written by Joe Bloggs
Simple right? I'm glad you agree but read on because many people still get confused especially when trying to use them within the string.

When you need to use the single ' or double " inside a single quoted string you need to tell PHP to ignore it. The way this is done is to escape the quote within the string. To escape a character we use the \ slash. Example:
PHP Code:
//Single quote example
print 'This comment is from Joe Bloggs\'s blog.';
//Note the use of \'

//Double quote example
$Author 'Joe Bloggs';
print 
"$Author said \"This is my comment.\""
The two examples above will output the following:
Quote:
This comment is from Joe Bloggs's blog.
Joe Bloggs said "This is my comment."
Ok, so you've see how to escape quotes to use them within their own type of quotes but what happens if we want to use the the opposite quote in our string? Well with single quotes anything you use there is handled literally so using a double quote inside a single quoted string will produce exactly that - a double quote. Inside a double quoted string a single quote can also be used with no escaping required.

Now what about using the \ within a string?
In single quoted strings you don't need to worry. Sometimes in double quoted strings you may need to escape it.
PHP Code:
//This will work
$Comment "I installed PHP on my c:\ drive.<br>";
print 
$Comment;

//This will also work:
$Comment "I installed PHP on my c:\\ drive.<br>";
print 
$Comment
The output from both of the above is the same in this scenario:
Quote:
I installed PHP on my c:\ drive.
I installed PHP on my c:\ drive.
It is only in some special situations you may need to escape the backslash but I've mentioned it just in case you need it.

So, lets return to the SQL above:
PHP Code:
$sql "INSERT INTO wall (author, message) VALUES ("' .$author. '", "'. $message. '")"
This will raise a parse error looking like:
Quote:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in.. <file name> <line number>
So, whats wrong with that then?
If you look at the SQL after the word VALUES it becomes clear that there is some complex quoting going on:
Code:
//We're already inside double quotes at the beginning and end of the SQL.
"' .$author. '", "'. $message. '"
As you can see, PHP see's double quotes there and does not know if you're terminating the string or trying to add something. Then we have a single quote, plus the addition of a variable before trying to add on another string containing another double quote.. before trying it all again!

So, what do we do with this? Well there are 3 ways really:
PHP Code:
//Put the single quotes inside the doubles
$sql "INSERT INTO wall (author, message) VALUES ('" .$author"', '"$message"')";

//But remember inside double quotes $Variables work.. So..
//Remove the excess double quotes and make it tidy:
$sql "INSERT INTO wall (author, message) VALUES ('$author', '$message')";

//Or..:
$sql 'INSERT INTO wall (author, message) VALUES (\'' .$author'\', \''$message'\')'
Now I'll quickly mention arrays here as there also seems to be a little confusion with those. There is no need to ever use double quotes UNLESS your Key is text with a variable (EG: "Key$I" - Where $I is a number):
PHP Code:
//Not needed - It will work but it will waste CPU cycles checking the Key for a variable:
$Array["Comment"] = 'This is a test.';

//Better way using less CPU cycles:
$Array['Comment'] = 'This is a test';

//With variables:
$Key 'Comment';

//Not great but it works:
$Array["$Key"] = 'This is a test.';

//Better:
$Array[$Key] = 'This is a test.'
All of the above will work but you don't always need the double quotes.

There may also be times when you wish to use functions or PHP commands in conjunction with your quoted text. The general thing you must realise is that a string (thats quoted text) is just a string of text. It is seen by PHP as just that - text. PHP will check double quoted strings for variables and replace them but it will not run PHP commands or functions inside a string. You should realise that single quoted strings will not to anything magical so the following example uses double quoted strings. Example:
PHP Code:
//This will not work:
$Comment "Joe blogg's latest blog is: print get_comment()";

//This will work:
$Comment "Joe blogg's latest blog is: " get_comment();

//This will work:
$Comment "Joe blogg's latest blog is: ";
print 
get_comment(); 
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.

Last edited by Fou-Lu; 10-06-2011 at 06:23 PM..
tangoforce is offline   Reply With Quote
The Following 3 Users Say Thank You to tangoforce For This Useful Post:
bullant (06-21-2011), low tech (06-21-2011), TrevorWeaver (07-01-2011)
Old 06-21-2011, 09:14 AM   PM User | #2
abduraooft
Supreme Master coder!

 
abduraooft's Avatar
 
Join Date: Mar 2007
Location: N/A
Posts: 14,680
Thanks: 158
Thanked 2,182 Times in 2,169 Posts
abduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really niceabduraooft is just really nice
Quote:
//But remember inside double quotes $Variables work.. So..
//Remove the excess double quotes and make it tidy:
$sql = "INSERT INTO wall (author, message) VALUES ('$author', '$message')";
When using an associative array variable inside the string, wrap it by curly braces, like

PHP Code:
$sql "INSERT INTO wall (author, message) VALUES ('{$Data['author']}', '{$Data['message']}')"
__________________
Quote:
The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)
abduraooft is offline   Reply With Quote
Old 06-21-2011, 10:09 AM   PM User | #3
bullant
Banned

 
Join Date: Feb 2011
Posts: 2,699
Thanks: 13
Thanked 395 Times in 395 Posts
bullant is on a distinguished road
Quote:
Originally Posted by tangoforce View Post
Many new PHP coders will come across this error and will be a bit confused by what it means so I thought I would supply a quick topic to cover the issue in more detail.

Lets suppose we have the following code:
PHP Code:
$sql "INSERT INTO wall (author, message) VALUES ("' .$author. '", "'. $message. '")"
That is one line of PHP containing an SQL statement. To the experienced eye its defective but to a lot of new PHP programmers this looks fine.
More often than not, when a query is not returning the results you expect, there is a syntax error in the query itself.

I find the easiest and quickest way to check what the actual query about to be run is, is to echo it to the browser and syntax errors should then be fairly obvious.

For more complex queries a good practice imo is to first get the query working in the SQL GUI of your choice and then transfer the query to your server side script.

Debugging an sql statement in an sql gui is usually a lot easier than trying to debug it in the server side script.

Last edited by bullant; 06-21-2011 at 10:11 AM..
bullant is offline   Reply With Quote
Old 06-21-2011, 10:46 AM   PM User | #4
Dormilich
Senior Coder

 
Dormilich's Avatar
 
Join Date: Jan 2010
Location: Behind the Wall
Posts: 2,882
Thanks: 9
Thanked 291 Times in 287 Posts
Dormilich is on a distinguished road
Quote:
Originally Posted by tangoforce View Post
Double quotes tell PHP to examine the string inside it and if there are any variables found, replace them with their values. There is however a trade-off: PHP checks double quoted strings for variables it needs to replace - this uses more CPU cycles.
regarding the execution time, there is no indication that this would matter at all. (ref.)
__________________
please post your code wrapped in [CODE] [/CODE] tags
Dormilich is offline   Reply With Quote
Old 06-21-2011, 11:15 AM   PM User | #5
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,519
Thanks: 45
Thanked 440 Times in 429 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
Quote:
Originally Posted by bullant View Post
I find the easiest and quickest way to check what the actual query about to be run is, is to echo it to the browser and syntax errors should then be fairly obvious.

For more complex queries a good practice imo is to first get the query working in the SQL GUI of your choice and then transfer the query to your server side script.
I agree I frequently test SQL through phpmyadmin to see if it will work as expected and I always use mysql_error() where appropriate too.

It was rather late at night when I created this tip for the noobs so it's not perfect and the SQL was taken from another topic here as it looked like a good example to demonstrate with. Obviously in hindsight I may have got that wrong but hey ho I tried!
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.
tangoforce is offline   Reply With Quote
Old 06-21-2011, 11:28 AM   PM User | #6
bullant
Banned

 
Join Date: Feb 2011
Posts: 2,699
Thanks: 13
Thanked 395 Times in 395 Posts
bullant is on a distinguished road
Quote:
Originally Posted by tangoforce View Post
Obviously in hindsight I may have got that wrong but hey ho I tried!
no problem

I wasn't trying to suggest anything you posted was wrong. You made very valid points which should help at least noobies.

The purpose of my post was basically to add to your tips but it may not have come across as so .

Last edited by bullant; 06-21-2011 at 11:30 AM..
bullant is offline   Reply With Quote
Old 06-21-2011, 12:17 PM   PM User | #7
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,519
Thanks: 45
Thanked 440 Times in 429 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
No, no, you got it right, it was a bit daft of me in hindsight to use SQL as an example but I found it in another topic and it looked perfect for a tip topic! In hindsight SQL, strings and quotes are entirely different but there we go, thats the kind of silly things i do at 1am!

When I first started learning php I never had access to a reliable connection so I had to learn a lot the hard way using localhost and a local copy of the php manual. I had to figure out a lot of stuff myself with no-one to ask (you know, the silly things that take hours to figure out like the IE bug in my sig) so I figured these tip topics could be pretty useful in helping others and answering those little silly things that aren't always immediately obvious.
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.
tangoforce is offline   Reply With Quote
Old 06-21-2011, 02:45 PM   PM User | #8
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,662
Thanks: 4
Thanked 2,452 Times in 2,421 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Good.
Added to the FAQ thread.
Fou-Lu is offline   Reply With Quote
Old 07-01-2011, 06:24 PM   PM User | #9
TrevorWeaver
New Coder

 
Join Date: Jun 2011
Posts: 29
Thanks: 13
Thanked 3 Times in 3 Posts
TrevorWeaver is an unknown quantity at this point
Thanks for your concise explanation.

Seems I was wrong but that is nothing new....was just trying to be helpful....so thanks for pointing me in the right direction.

Regards Trevor
TrevorWeaver is offline   Reply With Quote
Old 10-06-2011, 04:37 PM   PM User | #10
coin
New Coder

 
Join Date: Sep 2011
Posts: 24
Thanks: 1
Thanked 3 Times in 3 Posts
coin is an unknown quantity at this point
You accidentally threw an extra double quote in on your last example.
PHP Code:
//This will work:
$Comment "Joe blogg's latest blog is: " .get_comment()"; 
Should be
PHP Code:
//This will work:
$Comment "Joe blogg's latest blog is: " .get_comment(); 
coin is offline   Reply With Quote
Old 10-06-2011, 04:58 PM   PM User | #11
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,519
Thanks: 45
Thanked 440 Times in 429 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
Yes I'm aware of that but unfortunately I can't edit the post. The forum locks it after a few minutes.

It's not the only one, if you look closely there is also a few ' marks too but I did submit the article at 1:56am
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.
tangoforce is offline   Reply With Quote
Old 10-06-2011, 05:53 PM   PM User | #12
Inigoesdr
Super Moderator


 
Inigoesdr's Avatar
 
Join Date: Mar 2007
Location: Florida, USA
Posts: 3,602
Thanks: 2
Thanked 398 Times in 391 Posts
Inigoesdr is a jewel in the roughInigoesdr is a jewel in the roughInigoesdr is a jewel in the rough
Fixed.
Inigoesdr is offline   Reply With Quote
Old 10-06-2011, 06:05 PM   PM User | #13
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,519
Thanks: 45
Thanked 440 Times in 429 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
Thanks Inigoesdr, Any chance you could fix these two as well? - They're quotes:

Comment written by $Author'
Comment written by Joe Bloggs'

Both have an ' at the end. Sorry about that, no idea how I missed those when I previewed so many times
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.
tangoforce is offline   Reply With Quote
Old 10-06-2011, 06:23 PM   PM User | #14
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,662
Thanks: 4
Thanked 2,452 Times in 2,421 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Quote:
Originally Posted by tangoforce View Post
Thanks Inigoesdr, Any chance you could fix these two as well? - They're quotes:

Comment written by $Author'
Comment written by Joe Bloggs'

Both have an ' at the end. Sorry about that, no idea how I missed those when I previewed so many times
Done. Not a huge deal with the output, but easier than explaining after its a typo lol.
Fou-Lu is offline   Reply With Quote
Old 10-06-2011, 06:38 PM   PM User | #15
tangoforce
Senior Coder

 
tangoforce's Avatar
 
Join Date: Feb 2011
Location: Your Monitor
Posts: 3,519
Thanks: 45
Thanked 440 Times in 429 Posts
tangoforce will become famous soon enoughtangoforce will become famous soon enough
Thanks Fou
__________________
Please wrap your code in [php] tags. It is a sticky topic and it HELPS us to HELP YOU!
TIP: Coding styles and $end errors :::::::::: TIP: Warning: Cannot modify header information - headers already sent :::::::::: TIP: Quotes / Parse error: syntax error, unexpected T_..
PHP Code:
//Please don't use this for your form processing:
if (isset($_POST['submit']))
//Internet explorer has a bug and does not always send the submit value. 
Explanation: The IE if(isset($_POST['submit'])) bug explained.
tangoforce is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:44 PM.


Advertisement
Log in to turn off these ads.