Woodstock
Woodstock

Reputation: 22926

Strange behaviour with MySQL and PHP pdo, whats wrong?

I'll try to be concise and only show relevant information here:

I have two nearly identical pieces of code, one which works and the other not.

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

$result = $query->fetchall((PDO::FETCH_ASSOC));
var_dump($result);

The above code works, when I var dump the query it looks like this:

SELECT * FROM active_notifications WHERE direction = '>' AND 182.62000 > trigger_price AND currency = '$'

My problem occurs when I try with a slightly different piece of code where I swap the $ symbol for a £ symbol

Here is the code:

$query = $pdo->prepare("SELECT * FROM active_notifications WHERE direction = '>' AND $gbpCurrent > trigger_price AND currency = '£'");
$query->execute();  
var_dump($query);

$result = $query->fetchall((PDO::FETCH_ASSOC));

var_dump($result);

When I var dump the query I get this:

SELECT * FROM active_notifications WHERE direction = '>' AND 114.19942 > trigger_price AND currency = '£'

So all is correct up to this point,

When I run either created query directly in PhpMyAdmin the expected results are returned, However when I var_dump the $result of the £gbp query I get a null array.

At first I though it might be because I was reusing variable names but I tried both in complete isolation, the USD query always works and the GBP never works and always results in a null array being returned.

Like I said both of the generated queries work correctly in PhpMyAdmin (when run directly against the database)

The only difference is that in one query I have a £ symbol and the other I have a $ symbol,

Is the £ symbol some kind of disallowed symbol in PHP or something like that?

Thanks, John

Upvotes: 1

Views: 62

Answers (1)

Shomz
Shomz

Reputation: 37701

Check php and mysql character encodings. I'm thinking that your php's £ is not the same as your mysql's £.

Ideally, you'd avoid all the mess by using 'gpb', 'usd', etc... for the currency field.

From the OP:

I just slapped this into my pdo init : PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" and all is good.

Upvotes: 3

Related Questions