I’ve only actually made a point of getting to grips with PHP’s PDO library in the last week, and this morning have run into a strange problem which I’m hoping someone can shed some light on for me.
FWIW, I’m using ODBC to connect to SQL Server 2005.
It seems that when I bind a value to a parameter in a join condition, if the value is a string, it is converted to the TEXT datatype which is incompatible in SQL Server with the equality operator. But as soon as the parameter is moved into the query’s WHERE clause, it executes fine.
Here’s some code which gives an example of this happening.
$query = $db->prepare('SELECT * FROM posts_tags WHERE tag = :tag');
$query->bindValue(':tag', 'example', PDO::PARAM_STR);
$query->execute(); // works fine
$query = $db->prepare('SELECT * FROM posts p INNER JOIN posts_tags t ON p.id = t.post_id WHERE t.tag = :tag');
$query->bindValue(':tag', 'example', PDO::PARAM_STR);
$query->execute(); // works fine
$query = $db->prepare('SELECT * FROM posts p INNER JOIN posts_tags t ON p.id = t.post_id AND t.tag = :tag');
$query->bindValue(':tag', 'example', PDO::PARAM_STR);
$query->execute(); // produces below error
Error message:
SQLSTATE[42000]: Syntax error or access violation: 402 [Microsoft][ODBC SQL Server Driver][SQL Server]The data types varchar and text are incompatible in the equal to operator. (SQLExecute[402] at ext\\pdo_odbc\\odbc_stmt.c:133)
Does anyone know how I can stop this error from occurring?