0

Suppose I have this query:

SELECT * FROM 'users' WHERE ( username = 'foo' OR email = 'bar' )

How would I make it so, that query uses ? marks instead of passing values in directly. eg.

SELECT * FROM 'users' WHERE ( username = ? OR email = ? ... 

And have input specified within WHERE () clauses if possible.

EDIT: I've read somewhere a while ago that using ? marks in queries improves performance and helps with sql injections. This is what I am trying to do here.

5
  • What flavour of SQL? Typically this would be a function of the client/code that is sending the query to the database server Commented Feb 18, 2013 at 0:44
  • ? is used to define place holders. And are used with prepared statements. What is it that you are trying to do? Commented Feb 18, 2013 at 0:48
  • I am trying to do SELECT * FROM 'users' WHERE ( 'username = ? OR email = ?', 'foo', 'bar') so foo and bar replace placeholders. Commented Feb 18, 2013 at 0:56
  • Are you executing your SQL from the mysql/psql interface? From within a procedure? Or perhaps through some language's database interface? And are you using MySQL or PostgreSQL? I'm guessing the former since PostgreSQL would complain about 'users'. Commented Feb 18, 2013 at 1:31
  • Executing from mysql shell. Commented Feb 18, 2013 at 5:08

1 Answer 1

8

In MySQL, the question mark symbol that you can find in your query is called the parameter placeholder. It is usually used when you are creating a Prepare statement (dynamic sql). ex,

SET @s = 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
PREPARE stmt2 FROM @s;
SET @a = 6;
SET @b = 8;
EXECUTE stmt2 USING @a, @b;

UPDATE 1

here's an example of select based on your data above,

SET @s = 'SELECT * FROM tableName WHERE username = ? and email = ?';
PREPARE stmt2 FROM @s;
SET @a = 'foo';
SET @b = 'bar';
EXECUTE stmt2 USING @a, @b;
Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible to fill placeholders and execute SELECT query in single command?
what do you mean by fill placeholders? you can create a stored procedure from that.
Im wondering if its possible to use placeholders, provide values for placeholders and execute query in same sql command.
if that's the case, why do you still want to use place holders when you have already a value in line on the query?
oh yea, now I understand what ? marks do. And I figured out how to use them in the ORM Im using. Like so: User.where("username = ? OR email = ?", username, email)[0]

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.