database question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nawhaley
Forum Commoner
Posts: 85
Joined: Wed May 18, 2005 11:43 am

database question

Post by nawhaley »

heres a quick question for you guys. I'm currently working on a database app for my company. It pulls questions then answers from various tables then waits on a customers response before going to the next question. Now what I'm curious about is can you use variables in SQL statments in php? I'm thinking of something long the lines of the following

Code: Select all

$sql = &quote;Select Questioncode from tblQuestion where Questioncode =&quote; .&quote;$qcode&quote;;
or would I need to do more of a case statement using qcode?

I would prefer the first method because it would be easier to manage than making an unreasonably large case statment that makes an individual statement based of $qcode. Not to mention I don't know exactly how many questions are going to be put into the database for them to be quized on so it makes doing it by case even more of a bad idea.
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Re: database question

Post by nielsene »

Gemerally speaking, yes you can do that. And using normal PHP variable interpolation rules, you could right this simply as:

Code: Select all

$sql = &quote;Select Questioncode from tblQuestion where Questioncode =$qcode&quote;;
Now if Questioncode is a CHAR/VARCHAR/TEXT type you'll want to quote it, so

Code: Select all

$sql = &quote;Select Questioncode from tblQuestion where Questioncode ='$qcode'&quote;;
but as PHP will interpolate the variables in double-quotes, and SQL wants the single quotes, everything works nicely and keeps the synatc rather clean.
nawhaley
Forum Commoner
Posts: 85
Joined: Wed May 18, 2005 11:43 am

Post by nawhaley »

great glad to know the idea wasnt to far of the mark thanks :).
Post Reply