2

I have a name stored in the variable username and would like to pull users row information when I try

result = dbh.query("SELECT * FROM maintab WHERE user = '#{username}'")

I get no results. If I put in the username by hand however, it does return a result. How format my query so that I may use variables?

4
  • 3
    Watch out for en.wikipedia.org/wiki/SQL_injection Commented Apr 1, 2011 at 6:58
  • Thanks for the warning, I'll be sure to injection attack proof all my queries once I actually get everything working. Commented Apr 1, 2011 at 7:27
  • are you sure that username variable isn't nil or emty? Commented Apr 1, 2011 at 7:34
  • I would recommend using something a little more high level like github.com/jeremyevans/sequel DB[:maintab].filter(:user => username) or DB['select * from maintab where user = ?', username] Commented Apr 1, 2011 at 8:34

2 Answers 2

3

Try to debug this way:

username = "Peter" # any of your real name
result = dbh.query("SELECT * FROM maintab WHERE user = '#{username}'")

it should work. Looks like your username is nil or blank

Sign up to request clarification or add additional context in comments.

3 Comments

Crazy: I was putting the username in via gets on screen and output the variable just to make sure it was there and it was. However when I set username like you did above it worked. Turns out there was something extra on the variable and .strip clears it right up. Thanks.
@Arbiter: You were saying something about getting it working before worrying about data cleansing (i.e. SQL injection)...
I was stupidly assuming that the gem just had trouble with using variables in queries. That'll teach me...
0

Open up IRB and try to print what you have.

How does #{} behave with single quotes vs escaped double quotes?

That should answer your question.

1 Comment

I'm not exactly sure if I can try the IRB. Im running a script on a remote server. I have it put out the number of rows it finds to see if it found anything. I believe I correctly tried the escaped double quotes and met the same result. Its very possible that I did it incorrectly though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.