Woodstock
Woodstock

Reputation: 22926

Comparing floats in SQL, PHP

I have the following SQL executing:

$query = $pdo->prepare('SELECT * FROM active_notifications WHERE direction = ">"
AND trigger_price > "$floatUsdTrigger" ');

If I replace $floatUsdTrigger with a number, it works as expected; however it fails to work with my $floatUsdTrigger variable. This variable is a float cast as a string, and when I do a vardump it looks correct e.g (float) 120.00.

My trigger_price is a varchar[10], and like I said is fine when I replace the $floatUsdTrigger with a number; any ideas?

I did a good amount of research and couldn't find an answer to this; as an objective C developer, I find PHP to be infuriatingly "loose" at times.

Upvotes: 1

Views: 76

Answers (2)

gen_Eric
gen_Eric

Reputation: 227200

You are using ->prepare, please don't use variable interpolation with this!

Do it like this:

$query = $pdo->prepare('SELECT * FROM active_notifications WHERE direction = ">" AND trigger_price > ?');
$query->execute(array($floatUsdTrigger));

while($row = $query->fetch()){
    // var_dump($row);
}

Upvotes: 4

AbraCadaver
AbraCadaver

Reputation: 78994

The $floatUsdTrigger var isn't parsed inside single quotes. You would see this if you echo out that string.

Suggestion: use double quotes for the entire string and use single quotes around text values that are part of the query.

Upvotes: 3

Related Questions