Jump to content
Larry Ullman's Book Forums

Php Variables In Mysql Query


Recommended Posts

I have got all the examples in the book to work, but when I change anything a bit of trial and error is often required. I have just spent a couple of hours searching the internet for a complete set of rules about including PHP variables in a mySQL query -- and failed. But got lots of conflicting advice. And even the few rules I've found (eg. INT variables don't need single quotes but STRINGS do) seem to get broken by Larry -- eg. sometimes you use $uid, sometimes '$uid' ).

 

And I've read that arrays need enclosing in curly braces {}, and some people say you shoud always enclose all variables in these to make things easy and consistent. I note Larry uses them in a few places in the book.

 

In summary, I'm confused. Please can anyone point to a good article or tutorial, or give some tips.

Link to comment
Share on other sites

I think part of the confusion comes from these things being context sensitive. If you could provide examples of where, say, I use $uid and where I use '$uid', I could explain that in particular. Again, context matters here, but in terms of PHP variables in queries, the most important thing is that your query uses double quotation marks or uses single quotation marks and concatenates the variables in. You must wrap arrays in curly braces if it's an associative array. Indexed arrays do not need to be wrapped. I wouldn't say you should always use them, as that's just tedious and unnecessary, but I appreciate the attempt to be consistent.

 

Second, there's the issue of values in MySQL queries, which is separate from, but affects, the use of PHP variables. Numbers and function calls should not be quoted but strings and dates must be.

 

Also keep in mind that there's a difference between what you MUST do and what you SHOULD do. You must quote strings in queries and if you don't, the query will fail. You should not quote numbers, but if you do, the query will still work, just not as optimally.

Link to comment
Share on other sites

Thanks Larry

 

I think my hope of a simple set of rules is not possible :-)

 

To your explanation I think we need to add that variables must be enclosed in quotes, unless they are Table names or some such, in which case no quotes??

Link to comment
Share on other sites

yeah, there is no simple set of rules. But continuing on, table and column names never go in quotes. Some people put them in backticks, and if they conflict with a MySQL keyword, you must use backticks. It's not a matter of putting variables in quotes or not, but rather whether the variable's value needs to be quoted (in which case you would quote the variable to get that effect).

Link to comment
Share on other sites

 Share

×
×
  • Create New...