Type conversion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nathj
    Recognized Expert Contributor
    • May 2007
    • 937

    Type conversion

    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
  • mwasif
    Recognized Expert Contributor
    • Jul 2006
    • 802

    #2
    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]

    Comment

    • nathj
      Recognized Expert Contributor
      • May 2007
      • 937

      #3
      Originally posted by mwasif
      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

      Comment

      • kovik
        Recognized Expert Top Contributor
        • Jun 2007
        • 1044

        #4
        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.

        Comment

        • nathj
          Recognized Expert Contributor
          • May 2007
          • 937

          #5
          Originally posted by volectricity
          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

          Comment

          Working...