0

I am trying to make a form that has several checkboxes input the value of each checked checkbox into a saeparate row on my mySQL database.

Here is my HTML:

<form action="testsent.php" method="post" novalidate>
  <div id="currentWork">
<label for="currentWork">Mark all that apply.</label><br>
  <input type="checkbox" name="chk1[]" value="Bernards Township">Bernards Library<br>
  <input type="checkbox" name="chk1[]" value="Boonton Holmes">Boonton Library<br>
  <input type="checkbox" name="chk1[]" value="Butler">Butler Library<br>
  <input type="checkbox" name="chk1[]" value="Chatham">Chathams Library<br>
  <input type="checkbox" name="chk1[]" value="Chester">Chester Library<br>
  <input type="checkbox" name="chk1[]" value="Denville">Denville Library<br>
  <input type="checkbox" name="chk1[]" value="Dover">Dover Library<br>
  <input type="checkbox" name="chk1[]" value="East Hanover">East Hanover Library<br>
</div>
<input type="Submit" value="Submit" name="Submit"/>
</div>
</form>

And here is my PHP:

if(!empty($_POST['chk1'])) {
foreach($_POST['chk1'] as $check) {
        //echo $check;
        $sql="INSERT INTO $usertable (library) VALUES ('.$check.')";
 }
}

if(mysqli_query($link, $sql)) 
    {
        echo 'Thanks for submitting';
    } 
else {
        echo 'ERROR: Could not execute $sql.' . mysqli_error($link);
    }

This is WORKING except it only inputs the final item checked. If Boonton is checked as well as Chester and Denville, it will only input 'Denville' into the form.

I thought having a foreach loop will iterate over the checkboxes, but I'm not sure where I'm going wrong. I'm not getting any error messages. I have clicked every single link that comes up when I search for this problem on stackoverflow. The problem is that there seems to be so many different ways to make this work and most of these questions are marked as having not enough information or being too generic.

If there's ANY extra info you need in order to help me resolve this, I'll be glad to provide it! I'm holding nothing back. Thanks!

9
  • Well for starters, you're not writing anything to your database. Secondly, you're dumping user-supplied data into an SQL query. Good way to get hacked! Commented Sep 12, 2018 at 20:17
  • I don't see a <form> element Commented Sep 12, 2018 at 20:19
  • @miken32 I must be writing something though, because when I submit the form, a value does appear in my database under the 'Library' column. Commented Sep 12, 2018 at 20:20
  • @ryantxr yes, I omitted that part, I can add it to the original post now. Commented Sep 12, 2018 at 20:21
  • 1
    You are writing to the database outside of the loop. Therefore, you are only inserting the last one. Move mysqli_query($link, $sql) inside the loop. Commented Sep 12, 2018 at 20:29

1 Answer 1

2

You're writing to the database outside the loop. So the only value written is the last one that went through the loop. Move your insert into the loop.

if(!empty($_POST['chk1'])) {
    foreach($_POST['chk1'] as $check) {
        //echo $check;
        $sql="INSERT INTO $usertable (library) VALUES ('.$check.')";
        mysqli_query($link, $sql);
    }
}

What you need to be doing is using prepared statements to sanitize user data. This will also be much more efficient as the query is only sent to the database once:

if (!empty($_POST["chk1"])) {
    $stmt = $mysqli->prepare("INSERT INTO $usertable (library) VALUES ?");
    $stmt->bind_param("s", $check);
    foreach($_POST['chk1'] as $check) {
        $stmt->execute();
    }
    $stmt->close();
}
Sign up to request clarification or add additional context in comments.

7 Comments

This is exactly what I was looking for. Thanks for the info on sanitizing user data. The input is going in like '.Denville.' with the periods on either side.I tried the second code, the sanitized one, and I got this error: 'Call to a member function prepare() on null in /home/mainlib/public_html/subs/testsent.php on line 29'
Well of course you’ll need to ensure $mysqli is a properly initialized mysqli connection.
Oh, I see, so in other words everything should match. Makes good sense! Thank you so much, I really appreciate it. I work for a small business with very few resources for training employees and I've offered to learn to collect and analyze data and this is a huge help to go alongside what I can pick up in books/online courses.
The issue seems to be with the line: '$stmt->bind_param("s", $check);' I have checked that the statement is initialized. Still an error. But the un-sanitized version works fine and nothing has changed, how can that be?
Sorry to comment again - can't edit my original. The only thing that differs from the 'working' code and the 'sanitized' code is that the Value is "?" which calls to the foreach loop right? Could this have something to do with the form submitting unchecked checkboxes as false? Even when I check every box, I get the same error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.