Query only works w/ smart quotes?
I'm using PHP to connect to a MySQL db, and the following query only works w/ Microsoft's silly smart quotes around the table name, but not regular ones.
$query = "SELECT * FROM `ajax-zipcodes` WHERE zipcode='$zip'"; (works)
$query = "SELECT * FROM 'ajax-zipcodes' WHERE zipcode='$zip'"; (doesn't)
If I try to execute a query I get the following error whenever I try to access the returned object:
Quote:
Notice: Trying to get property of non-object in C:\Documents and Settings\dunniana\My Documents\Web Design\Playground\AJAX\Zip Code\getCityState.php on line 22
Any ideas?
Greg K posted this at 22:48 — 15th August 2005.
He has: 2,145 posts
Joined: Nov 2003
The ` character (I always called it a "backquote", mysql reference calls it a "backtick".) is what mysql uses to wrap field, table and database names. That is just hte way it was programmed. If you are not using anythng special in the names, you don't need them
ie. SELECT payrate FROM employees
However, if you ever use a variable for the field,table or db name, wrap it in the quote.
ie $sql = "SELECT payrate FROM `" . $employeeTable . "`"
The current project I maintain, about a year ago I ran into this problem. couldn't figure out why a new user crashed out. Here it was becasue of the hyphen in the username he picked.
I quickly realized they were needed, especially in case someone created a username that happened to be a keyword in mySQL (ie. create, select, insert, from, where)
ie. User WHERE tries to get data via above example sql statement, but without the backticks, would translate to this SQL being issued to the server: SELECT payrate FROM where (I'm sure you can see the problem here). With backticks, you get SELECT payrate FROM `where`
-Greg
IanD posted this at 22:55 — 15th August 2005.
They have: 222 posts
Joined: Sep 1999
I took the quotes off of the table name and put them around the variable and am still getting the error message about the query result not being an object
$query = "SELECT * FROM ajax-zipcodes WHERE zipcode=`" .$zip. "`";
Fighting for a Lost Cause.net
Greg K posted this at 22:57 — 15th August 2005.
He has: 2,145 posts
Joined: Nov 2003
You still need them around the table name becasue of the hyphen in there. My reference to using them around a variable was if you are using the variable in place of a field name, table name or db name (which you are not).
-Greg
IanD posted this at 23:18 — 15th August 2005.
They have: 222 posts
Joined: Sep 1999
Ah, that's it. Thanks
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.