views:

28

answers:

2

Rather new to php, so sorry if this seems stupid. I'm really copying a lot of this from previously written code from other developers at my company.

The way we run a query is basically like this:

$qry = new SQLQuery;
$sqlString = "SELECT * FROM database.table WHERE table.text = '" . 
              $textVar . "' and table.text2 = '" . $text2Var."'";
$qry->prepare(String::Condense($sqlString));
$qry->execute();

The problem I'm having is that $textVar or $text2Var may legitimately have question marks (?) in them as part of their text, this is causing the query SQLQuery class to break treating the question mark as a variable I'm not passing it.

So how can I instruct the SQLQuery class to ignore question marks?

p.s. I'm sure there's terminology for a lot of this that I don't know, please keep that in mind when giving me an answer.

+2  A: 

You want your prepared statement $sqlString to have ? where you are putting $textVar and $text2var, and then you need to bind those to the statement.

It's treating them as placeholders because they look like placeholders when you prepare your SQL.

So:

$sqlString = "SELECT * FROM database.table WHERE table.text = ? and table.text2 = ?"

You should take a look at MySQL Prepared Statements and familiarize yourself with how they work and what benefits they provide.

jasonbar
So lets say I switch it to look like `WHERE table.text = '?' and table.text2 = '?'";` and then I feed it the variables, even if the variables have `?` as part of their text it will be OK? Do I have to prepare if my `$sqlString` is ready to go? if so how do I execute the query without preparing?
invertedSpear
@invertedSpear: I don't know what DB wrapper you are using so it is hard to answer. You **want** to use prepared queries, though, so you don't have to worry about sanitizing everything. And yes, your values will be able to have ?s in them, no problem.
jasonbar
Wish I knew more about php so I could ask a better question. I'll switch it all over to prepared/parametered statements. Thanks for your help
invertedSpear
A: 

It kinda looks like some PDO derivative so it should probably be something more like:

$qry = new SQLQuery;
$sqlString = 'SELECT * FROM database.table WHERE table.text=? AND table.text2=?'
$qry->prepare($sqlString);
$qry->execute(array($textVar, $text2Var));
Kris