PHP Inserting Multiple Checkbox and Textbox Arrays into MySQL Database

PHP inserting multiple checkbox AND textbox arrays into MySQL Database

You shouldn't be using implode. That puts a comma-separated list of everything in the form into each row that you insert, and repeats this for every box that's checked. You should just insert one item in each row, by indexing the arrays.

However, when you have a checkbox in a form, it only submits the ones that are checked. The result of this is that the indexes of the $_POST['checkbox'] array won't match up with the corresponding $_POST['item'] and $_POST['quantity'] elements. You need to put explicit indexes into the checkbox names so you can relate them.

<form method = "POST">

<input type = "hidden" name = "item[]" value = "cupcake">
<input type = "text" name = "items" value = "cupcake" readonly><br>
<b>Price :</b> <span name = "price" value = "3.00">$17.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[0]" type="checkbox" value="17" /><span>Add to Cart</span></label></div></div></td><br>

<input type = "hidden" name = "item[]" value = "cake">
<input type = "text" name = "items" value = "cake" readonly><br>
<b>Price :</b> <span name = "price" value = "20.00">$20.00</span><br>
Quantity: <input tabindex="1" name="quantity[]" min="0" max="5" type="number" class="quantity" value="1" /><br>
<input tabindex="1" name="checkbox[1]" type="checkbox" value="20" /><span>Add to Cart</span></label></div></div></td><br>

<input type = "submit" name = "insertBT"><br>
</form>

Then your PHP code can be like this:

$stmt = $conn->prepare("INSERT INTO purchases (Product, Quantity, Price) VALUES (?, ?, ?)");
$stmt->bind_param("sis", $name, $quantity, $price);
foreach ($_POST['checkbox'] as $i => $price) {
$name = $_POST['name'][$i];
$quantity = $_POST['quantity'][$i];
$stmt->execute();
}

BTW, putting the prices in your HTML seems like a bad idea. Nothing stops the user from modifying HTML using the web inspector before they submit the form, so they could lower the price. You should get the prices from the database when processing the form.

Also, notice that in your original code you opened the database connection using MySQLi, but then you tried to do the insert using mysql_query instead of $conn->query(). You can't mix APIs like that; myql_query can only be used when you open the connection with mysql_connect.

Submit multiple checkbox together with textbox input value using PHP and MySQL?

You can use an IF statement if the checkbox is checked or not.

for ($j = 0; $j < count($_POST['selected_item']); $j++) {

if(!empty($_POST['selected_item'][$j])){ /* CHECK IF CHECKBOX IS SELECTED */

answer = mysql_real_escape_string($_POST['dynamic'][$j]); // returns multiple answers
$check_answer = "SELECT id, answer FROM answers WHERE answer = '$answer'";
$check_answer = mysql_query($check_answer); //checks if answer is exist in the database

while ($row = mysql_fetch_assoc($check_answer)) { // fetch a result rows as an associative array
$answer_id = $row['id']; // answer id from database
}

if (mysql_num_rows($check_answer) > 0) {
$q = "INSERT INTO correct_answer (question_id, answer_id) VALUES ('$counter','$answer_id')";
$q = mysql_query($q);
}
} /* END OF IF $answer is not empty */

} /* END OF FOR LOOP */

Advice:

Use a counter in your form and put it inside the array before submitting it. Example:

$counter = 0;

<input type="text" id="answer" name="dynamic[<?php $counter; ?>]" class="form_default" placeholder="answer" value="<?= isset($_POST['dynamic'][0]) ? $_POST['dynamic'][0] : '' ?>" required/>
<input type="checkbox" name="selected_item[<?php echo $counter; ?>]" id="chechbox" value="<?php echo $answer_id;?>">

Then increment it (assuming that you also run the form in a loop)

$counter = $counter + 1;

It doesn't run on a loop and the form is fix:

You can manually put the array number inside the textbox and checkbox.

After submission:

And when submitted, count the submitted checkbox using count() function of PHP.

$counter = count($_POST["selected_item"]);

Then run your loop using the $counter (refer back to my first given sample code).

Note:

  • The checkbox and it's corresponding textbox must have the same array number, or else, the answer will not match with the checkbox.

A much more simple example:

Answer # 1
<input type="checkbox" name="selected_item[0]"><input type="text" name="dynamic[0]"> <!-- Notice that they are both in 0 array -->

Answer # 2
<input type="checkbox" name="selected_item[1]"><input type="text" name="dynamic[1]"> <!-- Next question array should be incremented from the previous answer -->

And after submission, count the selected_item and then loop it that checks the selected checkboxes.

for($x=0; $x<=count($_POST['selected_item']); $x++){
if(!empty($_POST['selected_item'][$x])){
/**** PLACE HERE YOUR INSERT QUERY ****/
}
}

Insert multiple checkbox value with textbox value in database

textbox[ ] is a array. So Use $txt[$i]

$query="INSERT INTO message(item,quantity)  
VALUES('".$checkbox1[$i]."','".$txt[$i]."')";
^

Your Complete code with only one textBox

<b>
<li>
<img height="150" width="200"src="<?php echo $images_dir."/tb_".$row[2]; ?>"/>
<input type='checkbox' name='chk1[]' value ='<?php echo basename($images_dir."/".$row[2]);?>'/><input type='text' name='textbox'id='textbox'/> </br>

$checkbox1=$_POST['chk1'];

$txt=$_POST['textbox'];

if($_POST["submit"]=="submit") {
for($i=0;$i<sizeof($checkbox1);$i++) {
if(!empty($txt)) {
echo""
$query="INSERT INTO message(item,quantity) VALUES('".$checkbox1[$i]."','".$txt."')";
mysql_query($query) or die(mysql_error());
}
}
echo "message is send";
}

Inserting values from multiple checkboxes and textfields

Unchecked values are not submitted and checkbox quantity not same with textbox.
You should give input name array same keys :

$i = 0;
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[".$i."]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[".$i."]\"/></td>";
echo "</tr>";
$i++;
}

Use also this code:

$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
foreach ($checkbox as $key => $value)
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $value . "', '" . $_POST['moviecode'] . "', '" . $txt[$key] . "')";
mysqli_query($connect, $sqlqr);
}

Updating database with multiple checkbox values received from the loop?

What i understood is
1. you have array of 3 fields (cityid, cityorder, city status)
2. you are submitting all these values from the form
3. you want update cityorder and citystatus depends on cityid

The solutions is pretty simple

$i=0;
foreach($_REQUEST['cityOrder']) as $cityorder){

$cityID = $_POST["cityID"][$i];
$cityStatus = isset($_POST["cityStatus"][$i])?$_POST["cityStatus"][$i]:0;
$cityOrder = $_POST["cityOrder"][$i];

$updateCities = $db->execute("UPDATE cities SET city_status=?, city_order=? WHERE city_ID=$cityID", array($city_status, $cityOrder));

$i++;
}

How to INSERT multiple rows with multiple values, but only for items that have checkboxes ticked next to them

This isn't an entire solution but I see some problems:
You are looping through tracks and creating a new form for each one. The first problem is , you are missing the closing form tag. I guess the browser is automatically creating one, when it sees the next form start tag. ?? That's why you only get one single posted checkbox.
I would put all the track checkboxes into a single form. Then the posted trackid[] array will contain all the checked items.

[EDIT after your comment: The hidden fields albumid[] post the entire array, whereas the trackid[] checkboxes only post the actual checked boxes (HTML spec).

Instead of having albumid[], You could put the trackID and albumID together for the checkbox value, then parse them apart when you handle the post:
$value = $row['id']. ',' . $row['albumid'];
echo "<input type='checkbox' name='trackid[]' value='".$value."' />";

ALSO, the SQL, "INSERT INTO (..) .. VALUES (...) " only inserts one row.

It's easy to do that SQL in a loop for all the checked boxes.

foreach($_POST['trackid'] as $value) {
// parse the $value...
// SQL Insert...
}

EDIT 2: From my own comment:
Like hidden fields, input (text) field arrays also post the entire array (with empty values for blank inputs). (Again, this is not a PHP thing, it's a web browser standard to only post checked checkboxes and radio buttons. But ALL text and hidden INPUTs are posted.) So in your example, you need to code a mechanism to know which textbox goes with each checkbox. Quick and dirty...You could add a row index (0,1,2,3...) as another comma-separated number in your checkbox values, then you'll have the index into the posted textbox array. Alternatively, you could name the textboxes ' .. name="textinput_' . $row['trackid'] . '" ...' (not an array), then upon post, read them in your foreach loop with

$val = $_POST["textinput_{$trackid}"];

How to get PHP to match textbox with corresponding checkbox from a form

You could set up the price array to be indexed by customer IDs:

<input type="text" name="price[<?=$row['id']?>]" value="<?=$price?>" class="schedule_price">

... and then reference prices by customer IDs:

$customerIds = $_POST['customerid'];
$prices = $_POST['price'];

foreach ($customerIds as $customerId) {
$price = $prices[$customerId];
}

Select id_value from db into array checkbox and Insert multiple values from array checkbox to one column with comma separated

It should be

name="checkbox1[]"

Whereas you have

id="checkbox1[]"

Then when inserting the values in the database, you can do

$values = implode(",", $_POST["checkbox1"]);

PHP arrays: Also create a key-value pair for not-checked checkboxes

You can add an integer to the name of your checkboxes:

<form action="processingFile.php" method="post">
<input type="checkbox" name="filter[0]" value="1" checked="checked">
<input type="checkbox" name="filter[1]" value="1" checked="checked">
<input type="checkbox" name="filter[2]" value="1">
<input type="checkbox" name="filter[3]" value="1">
<input type="checkbox" name="filter[4]" value="1">
<input type="checkbox" name="filter[5]" value="1" checked="checked">
<input type="checkbox" name="filter[6]" value="1" checked="checked">
<input type="checkbox" name="filter[7]" value="1" checked="checked">
<input type="checkbox" name="filter[8]" value="1">
<input type="checkbox" name="filter[9]" value="1">
</form>

Submitting this and using print_r($_POST['filter']) will output:

Array
(
[0] => 1
[1] => 1
[5] => 1
[6] => 1
[7] => 1
)


Related Topics



Leave a reply



Submit