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 types (e.g. int), so if you query an int column, you get an integer in PHP instead of a string?
If you are running Ubuntu:
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:
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! :)
You could use type casting once you've pulled the data from your MySQL database
In MySQLi use
bind_result
: it sets the correct type and handlesNULL
.As PHP isn't a strongly typed language, this is somewhat meaningless, but you could of course simply cast the field in question to an int via settype, etc. prior to usage.
Irrespective, there's no way (that I know of) to maintain this "type" information automatically.
EX:
TABLE eletronics
PHP:
//result