jeudi 23 juillet 2015

checkbox doesn't send any data to mysql

world! I have simplest form of questionnaire (making it as a template for a future project) that contains text input, radio and checkboxes. The latter is pain in the ass, as I cannot figure out how do I make it work. Can anyone please have a look at my code and spot any problems in code? Also any recommendations on enhancing are welcomed.

<?php
if(isset ($_POST['submit'])){

    $con = mysql_connect ("localhost", "*********","*********");
if (!$con){
    die ("can not connect: " . mysql_error());
    }

mysql_select_db("dastiche_questionnaire",$con);
$offers = "None";
$sql = "INSERT INTO questionnaire (fname,sex,age) VALUES ('$_POST[fname]','$_POST[sex]','$_POST[age]')";


$chkbox = array('kiosk', 'tradecenter', 'bookstore');
$wherebuycard = $_POST['wherebuycard'];
    $values = array();
    foreach($chkbox as $selection ){
        if(in_array($selection, $wherebuycard)){
            $values[ $selection ] = 1;
            }
        else
            { $values[ $selection ] = 0;
            }
    } // end of foreach.

$sql = "INSERT INTO questionnaire (wherebuycard)
          VALUES ({$values['kiosk']}, {$values['tradecenter']}, {$values['bookstore']})";


mysql_query($sql,$con);

mysql_close($con);

}
?>

In the mysql database I have table with four columns named fname, sex, age, wherebuycard. "fname" is simple text input, "sex" is radio, "age" is dropdown and "wherebuycard" is checkbox. PHP shows no errors, but in mysql database there is no signs of data registration.

one clue: if I delete this portion of code:

$chkbox = array('kiosk', 'tradecenter', 'bookstore');
$wherebuycard = $_POST['wherebuycard'];
    $values = array();
    foreach($chkbox as $selection ){
        if(in_array($selection, $wherebuycard)){
            $values[ $selection ] = 1;
            }
        else
            { $values[ $selection ] = 0;
            }
    } // end of foreach.

$sql = "INSERT INTO questionnaire (wherebuycard)
          VALUES ({$values['kiosk']}, {$values['tradecenter']}, {$values['bookstore']})";

Then everything works (mysql receives data) except checkboxes.

Html bit:

<p><input type="checkbox" name="wherebuycard[]" value="kiosk"> kiosk</p>
<p><input type="checkbox" name="wherebuycard[]" value="tradecenter"> trade center</p>
<p><input type="checkbox" name="wherebuycard[]" value="bookstore"> book store</p>




Aucun commentaire:

Enregistrer un commentaire