开发者

php - Insert data from checkbox array into MySQL

开发者 https://www.devze.com 2023-02-24 08:47 出处:网络
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:

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 e.g.

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

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

精彩评论

暂无评论...
验证码 换一张
取 消