Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql automatically cast strings to integer

Tags:

php

mysql

I've just noticed that if I do a MySQL request like this one:

SELECT 1 FROM myTable WHERE id = 'asdf'

Then the string 'asdf' is casted to 0. It means that I have a record with id 0 this will match. The format of the id field is int(8).

What is the best way to proceed:

  • I need to check (by PHP for example) that my value is numerical only?
  • There is a MySQL way to do that?
  • I must remove my record with id 0? (bad)
like image 945
Yann Sagon Avatar asked Jun 11 '12 15:06

Yann Sagon


People also ask

How do I CAST a string in MySQL?

The CAST() function in MySQL is used to convert a value from one data type to another data type specified in the expression. It is mostly used with WHERE, HAVING, and JOIN clauses. This function is similar to the CONVERT() function in MySQL. It converts the value into DATE datatype in the "YYYY-MM-DD" format.

Can you CAST a string to an int in SQL?

CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER. TO_DATE converts a formatted date string to a date integer. TO_TIMESTAMP converts a formatted date and time string to a standard timestamp.

What is CAST () in MySQL?

The CAST() function converts a value (of any type) into the specified datatype.


3 Answers

Just write your queries so that they don't use numeric fields as if they were textual ones.

If id is a numeric field, then your where clause can never be useful. Yes, it would be good if MySQL actively complained about it - but fundamentally you shouldn't be writing code which runs bad queries to start with.

How did that query enter your system? Is the 'asdf' part direct user input? Can you use parameterized SQL instead?

If you're genuinely intending to query a numeric field, you should make sure that your input is numeric first. Convert the text to an integer in your calling code, not in the database.

like image 154
Jon Skeet Avatar answered Oct 19 '22 18:10

Jon Skeet


You must first sanitize your inputs via PHP.

$id = 'asdf';
if(is_numeric($id)){
    $query("SELECT 1 FROM myTable WHERE id = $id");
}else{
    die("ID is not numeric");
}

Or you can do:

    SELECT 1 FROM myTable WHERE id = 'asdf' AND 'asdf' REGEXP '^-?[0-9]+$'

This would cause the regex to = false, causing no rows to return.

like image 26
Mike Mackintosh Avatar answered Oct 19 '22 17:10

Mike Mackintosh


Since pdo prepared statements binding with correct types will not raise any error (except if mysql strict mode is enabled), your only choice is to ensure and control the types of your variables within your php to "correct" the permissivity of these languages.

[thanks to commentators]

like image 40
Sebas Avatar answered Oct 19 '22 16:10

Sebas