1

I have a php script that looks like this:

    $contacts["{$firstname}"]    =  $_POST["{$firstname}"] ;
$contacts["{$lastname}"]    =  $_POST["{$lastname}"] ;
$contacts["{$age}"]    =  $_POST["{$age}"] ;


    $collection->insert($contacts);

so this works fine but i all of these values are going into my collection as "fistname", "lastname" and "age" with quotes around all. I want the quotes around first name and last name but i want the age field to insert as a number/integer not a quoted string. How do I make sure that the age field and other numeric fields go into the mongodb/collection as a number?

I was thinking something like: integer -> $_POST["{$age}"] but im sure that's not right. Again im using PHP not the shell. Thnaks.

Thank you for your help.

1

3 Answers 3

4

First, you don't need all those quotes and braces. Second, try casting the value to an int

$contacts = array(
    $firstname => $_POST[$firstname],
    $lastname  => $_POST[$lastname],
    $age       => (int) $_POST[$age]
);

I'm assuming here that all the $_POST vars have been checked and validated and $firstname, $lastname and $age are all valid array key strings

Sign up to request clarification or add additional context in comments.

5 Comments

I tried your suggestion and although i am not getting any page errors it is still inserting as a "" string. Any other suggestions? Thanks.
Ooops, this did work. I actually had an error in my code. Once i fixed the error (int) worked perfectly. Thanks.
Do you know if there is a cheat sheet on these function like (int). Now my problem is i want to keep the decimal and the numbers after the decmal but (int) is stripping everything after the decimal. What function would i use to keep the decimal in there and the number after the decimal. Thanks.
@user982853 (int) isn't a function, it's a type cast. Try (double) for a decimal number
1

Simple, typecast to integer, and then do the insert:

$contacts["{$age}"]    =  intval($_POST["{$age}"]) ;
$collection->insert($contacts);

1 Comment

I tried your suggestion and although i am not getting any page errors it is still inserting as a "" string. Any other suggestions? Thanks
0

You can use http://php.net/manual/en/function.intval.php to convert a string to an integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.