When data is returned from MySQL, it is automatically returned as strings, regardless of the MySQL data type.
Is there any way to tell MySQL/PHP to maintain the data
PHP's default library for MySQL doesn't have any options of this kind. Use type casting like (int) or intval, (float) etc
If you are running Ubuntu:
sudo apt-get remove php5-mysql
sudo apt-get install php5-mysqlnd
sudo service apache2 restart
in php, you can use ([type]) to make sure $something was integer , this help sql injection if you khow about it.
ex:
(int) $something;
In MySQLi use bind_result: it sets the correct type and handles NULL
.
I don't know in what context you asked this question. Because the data type of a php variable is dependent on what data type a column in your table has. If the column has data type "int" in mysql, you get an integer in php (not a string).
But anyways, you can use either is_numeric(), is_int() or gettype() php functions to know the data type of a returned value from Mysql. The problem with is_numeric() is that it returns true even if a variable contains a numeric string e.g. "2". But gettype() will return "string" and is_int() will always return false in the example mentioned i.e. "2".
Once you know the data type of a returned value you can bind the php variable to maintain that type by type casting like this:
// Suppose this is the returned value from mysql and
// you do not know its data type.
$foo = "2";
if (gettype($foo) == "string"){
$foo = (string) $foo;
}
You can make several checks for what data type the variable has and then cast it accordingly.
I hope this reply would be helpful. Good luck! :)
If you want to get the values ordening by Price, you can change the Data Type to FLOAT from column (ex: price)
EX:
TABLE eletronics
price id
----------------
55.90 1
40.33 2
10.60 3
1596.90 4
56.90 5
PHP:
$sql = $pdo->query("SELECT * FROM eletronics ORDER BY price DESC");
//result
1596.90 4
56.90 5
55.90 1
40.33 2
10.60 3
//The order is being per prices //OBS: You can change the dots with "," using the str_replace() //result: 1596,90 - 56,90 - 55,90 - 40,33 - 10,60 etc.