0

I am having a bit of a problem, i am trying to store data with checkboxes, but i cant seem to figur it out. Right now i have made a script that can show multiple checkboxes all with the same name. So my question is now, how do i make the page where the data is sended to making them seperated? like:

<input type='checkbox' checked name='cpu-link[]' value='1' />
<input type='checkbox' checked name='cpu-link[]' value='2' />
<input type='checkbox' checked name='cpu-link[]' value='3' />

how can i get it stored for each checkbox in a new row in the mysql database? so it would be like:

  1. Data 1
  2. Data 2
  3. Data 3

And then i have a related qestion, how do i make so that the checkboxes that is not checked will get removed if they already is in the database. so if it is like this:

<input type='checkbox' checked name='cpu-link[]' value='1' />
<input type='checkbox' name='cpu-link[]' value='2' />
<input type='checkbox' name='cpu-link[]' value='3' />

Then the row with the id 2 and 3 will get removed but the row with id 1 will get created or just stay if it already is in the database.

It is all a kind of a link between 2 tables. I have a table with pc's in, and a table with hardware in. then i have the table with the links in, so if i choose a hardware that needs to bee in a machine, it will create a row in the link table so that when i display the pc, it shows with that hardware oppotionity.

sorry for my bad english. Thank You in Advance

4

1 に答える 1

0
$all_cpu_links = array(); // here is your array with all possible values of cpu-link
$previously_checked = array(); // array of values that are already in your database
$to_be_removed = array();
$to_be_inserted = array();

// It is better to use here here a prepared statement by the way
foreach ($_POST['cpu-link'] as $cpu_link)
{
    if (!in_array($cpu_link, $previously_checked))
    {
        // validate $cpu_link here
        mysql_query("INSERT INTO table (`cpu_link`) VALUES (".$cpu_link.");");
    }

}

foreach ($all_cpu_links as $cpu_link)
{
    if (!in_array($cpu_link, $_POST['cpu-link']) && in_array($cpu_link, $previously_checked))
        $to_be_removed[] = $cpu_link;
}

mysql_query("DELETE FROM table WHERE `cpu_links` IN (".implode(' ,', $to_be_removed).");");
于 2012-12-09T14:30:52.480 に答える