By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,462 Members | 1,057 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,462 IT Pros & Developers. It's quick & easy.

Type conversion

nathj
Expert 100+
P: 938
Hi,

I'm back with another question. This time I am conviced the answer is simple, I just can't find it anywhere.

I have a variable that comes from a drop down on a form. The variable may be somethig like "14", however, I need to write this to an integer field in a MySQL database.

So, how do I convert "14" to 14 so that I can use it in the database?

Cheers
nathj
Jul 24 '07 #1
Share this Question
Share on Google+
4 Replies


mwasif
Expert 100+
P: 801
You can use str_replace() to replace " from the input or the following RegEx to remove everything except numbers.

[PHP]echo preg_replace('/[^0-9]/', "", $_POST["value"]);[/PHP]
Jul 24 '07 #2

nathj
Expert 100+
P: 938
You can use str_replace() to replace " from the input or the following RegEx to remove everything except numbers.

[PHP]echo preg_replace('/[^0-9]/', "", $_POST["value"]);[/PHP]
Sorry it's taken me so long to get back to this one. I'm in the process of trying it out, if I come unstuck I'll post back with some code.

Cheers
nathj
Jul 27 '07 #3

kovik
Expert 100+
P: 1,044
PHP automatically converts numerical strings to numbers when used in mathematical operations and conditional statements, and MySQL does the same when assigning a string to a numerical field. Unless the quotes are actally in the string, you should be fine. If they are in the string, you may wish to rethink the values you are giving your to you dropdown options, as it is strange to put double quotes into the actual value.
Jul 27 '07 #4

nathj
Expert 100+
P: 938
PHP automatically converts numerical strings to numbers when used in mathematical operations and conditional statements, and MySQL does the same when assigning a string to a numerical field. Unless the quotes are actally in the string, you should be fine. If they are in the string, you may wish to rethink the values you are giving your to you dropdown options, as it is strange to put double quotes into the actual value.
volectricicty,

Of course! I don't know what I was thinking when I wrote that bit of code. I have sorted out the code that builds the drop down so that the value is not encased in quotes and all is well without any need for parsing the value.

On the plus side I have learnt something new, and have improved some more of my code. A good result all round.

Many thanks to all who posted.
nathj
Jul 27 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.