How to Insert Multiple Checkbox Values into a Data

2019-08-16 02:36发布

问题:

I've been working on this and searching the Web and coming up empty for the better part of two days. With a lot of sweat, I can insert one checkboxed value into a DB; however, if I check more boxes, it will still only insert one value.

Here is my code I'm using on input user page (with form tags excluded):

  <input type="checkbox" name="skills[]" value="1"> ActionScript<br />
  <input type="checkbox" name="skills[]" value="2"> AppleScript <br />

Now I'm grabbing two session variables to make link the selected skill to the user who is logged on:

  $skills = $_POST['skills'];
  $id = $_SESSION['Ind_ID'];

Here is the code that there is some small error in:

for ($i=0; $i<sizeof($skills);$i++) {
    // echo $skills[$i];
    $query= "INSERT INTO individual_skills(Skills_ID,Ind_ID) VALUES (" .$skills[$i]. ",
            ".$_SESSION['Ind_ID'].")";
 }

With my echo $skills[$i] I can see that I am looping and can display as many user inputs to the screen; so, that is the good news.

The issue is I can't get it to insert more than one value into a DB. I can do one value at a time; but, no more than one.

It seems my query is pretty close. It works perfect if I choose to select only one checkbox; however, if I select more than one, it only inputs the last value (so, if I have 10 values selected, it will insert the last value into the DB).

Any help, much appreciated.

I'm using PHP and MySQLi

UPDATED BASED ON FEEDBACK FOR LOOP Here is the updated loop. I have the query outside the loop, and now trying to APPEND to my initial query. Error says something is wrong with the syntax of the query.

$query= "INSERT INTO individual_skills(Skills_ID,Ind_ID) VALUES (" .$skills[$i]. ",
                                                        ".$_SESSION['Ind_ID'].")";

  for ($i=0; $i<sizeof($skills);$i++) {
  //echo $skills[$i];
  $query.= " VALUES (" .$skills[$i]. ",".$_SESSION['Ind_ID'].")";
  }

回答1:

Think about what your code is doing. Each loop, you're redefining the $query variable, so that when you get to the end, the final value of $query will be the last think you checked.

If you still want to use the same loop logic that you have written, which is probably not the most efficient way, then you'd have to execute the query each time within the loop, so that each query you write will be executed.

More precisely, the confusion seems to be stemming from the fact you haven't quite discovered the difference between assigning a value to a variable and passing a variable to a function for execution.



标签: php mysql mysqli