简体   繁体   中英

php - Insert data from checkbox array into MySQL

I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:

<div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>

There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:

regid | psc_1 | psc_2 | psc_3 | ...

My code:


    if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = @each ($boxes)) {
    $camp_string .= "'$camp',";
}
}

// The above to create a comma separated string

$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string; // To remove the trailing comma

$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");

The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.

I'm not sure what I'm missing.

-- Update#1 (in reference to a comment below)


if(!empty($_POST['camps'])) {
    $box=$_POST['camps'];
    while (list ($key,$val) = @each ($box)) {
    $camp_totals += $campcost[$val];
    echo "$campdesc[$val] - $$campcost[$val]
"; } }

Why not name the checkboxes something different like the names of the columns, so that your $_POST comes back as:

// print_r($_POST);
array(
     'regID' => 1,
     'camp_filmore' => 1,
     'camp_greenwald' => 1
     'camp_idunno' => 1
);

From there it's fairly simple to build your query:

$query = "INSERT INTO registered (".implode(array_keys($_POST), ", ") . ") ". 
    "VALUES (" . implode(array_values($_POST), ", ").")";

You should obviously check to make sure the values of $_POST are properly escaped and sanitized before inserting.

A nice trick to remove the trailing comma would be.

$camp_string = rtrim($camp_string,',');

Anyway your query is not formated correctly.

INSERT INTO camps_registered (regid,'psc_1', 'psc_2', 'psc_3') VALUES ($regid,psc_1', 'psc_2', 'psc_3')

You cannot have single quotes in the first bracket

I think you should be looking at implode and you can easily add addition strings to it...

so eg

$comma_seperated = implode(',', $boxes);

$subscribed = $regid . ',' .  $comma_seperated;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM