1

I found some code to help me with an issue I was having..it is so that if a form does not pass validation, it will retain my checkbox selections. Now I am wondering how do I get the selections in a form that i can put in mysql ? in my form

<?php

$a = array("1*","2*","3*","4*","5*+");

foreach($a as $key => $value)
{
    echo `"<input type='checkbox' name='rating[]' value='$value' `";

    if(is_array($_POST['rating']) && in_array($value,$_POST['rating']))
        echo " checked ";

    echo ">$value";
}
?>

<INPUT TYPE="SUBMIT" name="submitted" VALUE="Submit" class="submit">
</form>
</code>
1
  • if your value is in that array you will get the same answer allways and all will be 'checked' Commented Dec 14, 2010 at 21:21

1 Answer 1

2

Is this what you were asking for?

foreach($_POST['rating'] as $checked_value)
{
    //do what you want to do with here like INSERT or UPDATE
    echo $checked_value.'<br />';
}

EDIT: Perhaps too this will help if you are looking to do arithmetic or analysis on the ratings

    $a = array( "1" => "1*", "2" => "2*", "3" => "3*", "4" => "4*", "5" => "5*+");

    foreach($a as $key => $value)
    {
        echo '<input type="checkbox" name="rating[]" value="'.$key.'"';

    /* replaced
        if(is_array($_POST['rating']) && in_array($value,$_POST['rating']))
    with below */
        if(is_array($_POST['rating']) && in_array($key,$_POST['rating']))
            echo " checked ";

        echo " />$value";
    }

Not sure as to your implementation of this code but are you sure a checkbox is the correct input type? Perhaps a radio button would be better as users could only choose 1 rating. As it is currently set up, a user could choose 1, 3, and 5 as their rating.

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

5 Comments

+1 for good general point with the "multiple rating choice" bit
I am looking for a return of data like 1,3,5, your foreach got me closer but it is outputting like 135 instead. And yeah i want these to be multiple selectable.
I also tried the $key instead of rating but it throws it all off. It kills the postback in the checkboxes, I think thats due to it being a different value
sorry, meant instead of $value..not rating
check the update... I put a line break in between each one to make it clear they are being returned independently. You can format as desired. Also changed in_array($value, ... to in_array($key, ... Personally I find it desirable to echo output incrementally to both understand what my code is doing as well as understand values at particular points. Perhaps try that for future debugging and understanding?

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.