Search code examples
mysqlsqldatatypestype-conversion

Make MySQL not to convert string to number


I have a query in my application that selects users from a table by ID or by username:

SELECT * FROM users WHERE id = '$x' OR username = '$x'

This is working when given usernames like foo, bar123 or ids like 1, 123. But when I give a username like 2foo it selects both user 2foo and user with id=2. So it takes the 2 of 2foo and finds a user. Additionally I get a warning message: 1292: Truncated incorrect DOUBLE value: 2foo.

Is there a way to tell MySQL not to do this conversion (for this query but not whole db)? Or do I need to do a filtering after the query to discard false results?


Solution

  • Your query is formed in a way, that triggers a "this-is-a-feature-not-a-bug" behaviour in MySQL: You compare the same string ('$x') to a numeric field (id) and to a varchar field (username).

    While I am sure, there are ways to make this work in SQL, I suspect the only correct way is to fix the PHP that creates the query. Something like

    if (is_numeric($x)) $sql="SELECT * FROM users WHERE id = '$x' OR username = '$x'";
    else $sql="SELECT * FROM users WHERE username = '$x'";
    

    should help.

    Here is the SQL version, just for the sake of completeness:

    SELECT * FROM users WHERE id = IF('$x' REGEXP '^[0-9]+$','$x',0) OR username = '$x'
    

    Note: Form the OQ I assume, that $x is already escaped.