-1

I have multiple elements with checkboxes; on selecting a box, I want to store some of its attributes passed via the ajax data parameter into a database table. Here's an example of the JS and html markup.

$("input[type="submit"]").live("change", function() {
    if($(this).is(":checked")) {
        $.ajax({
            type: 'post',
            url: 'fetch.php',
            data:
                {
                    id: $(this).attr('id'),
                    checked: 'yes'
                }
        })
    }
})
<li>
  <label for="one"></label>
  <input type="checkbox" name="one" id="one">
</li>
<li>
  <label for="two"></label>
  <input type="checkbox" name="two" id="two">
</li>
<li>
  <label for="three"></label>
  <input type="checkbox" name="three" id="three">
</li>

However, as a PHP and mysql newbie, after succesfully connecting to my mysql table, I got stuck on the actual PHP code. The following doesn't do anything and I'm struggling to proceed.

<?php
if(isset($_POST['id'])){
  if (is_array($_POST['id'])) {
    foreach($_POST['id'] as $value){
      $query = "INSERT INTO my_table VALUES ". $value. ";";
      mysql_query($query) or die(mysql_error());
    }
  } else {
      echo "nothing checked";
  }
}
?>

Any help would be greatly appreciated.

  • Your checkboxs don't have a value set in HTML –  Jan 31 '18 at 22:15
  • 1
    It looks like $_POST['id'] will never be an array because each time you click a checkbox it sends exactly one id field. – James Jan 31 '18 at 22:16
  • What version of jQuery are you using? `.live()` was deprecated in 1.7 and removed in 1.9. You should use `.on()` for event delegation. – Barmar Jan 31 '18 at 22:21
  • Use `$("input[type='checkbox']").on("change", function() {` – Mark Schultheiss Jan 31 '18 at 22:24
  • I don't think the `change` event fires on submit buttons. You should be using `click`. And submit buttons can't be checked. – Barmar Jan 31 '18 at 22:24
  • That should be `$("#formid").on("click", ":checkbox", function() { ... })` – Barmar Jan 31 '18 at 22:25
  • @Barmar, yes or some such, I was editing my comment as you added yours, the "submit" point remains valid, no form to submit here in the OP post...can/should we assume that? Not sure. – Mark Schultheiss Jan 31 '18 at 22:29
  • @MarkSchultheiss My comment was intended for the OP. – Barmar Jan 31 '18 at 22:30

1 Answers1

0

Your INSERT query is not well formated.

Try something like this :

$query = "INSERT INTO my_table (column_name) VALUES ('". $value. "')";

Important note : Your code is vulnerable to SQL injections and may compromise the security of your database. You should use PDO or mysqli APIs to secure your SQL queries, and using prepare function.

Syscall
  • 19,327
  • 10
  • 37
  • 52