PHP inserting into database - complicated - php

I am trying to insert some values into a database from a form submitted by the user.
$id = mysql_insert_id();//Gets ID of last value inserted into related table
foreach( $_POST[ 'equipment' ] as $checkBoxIndex => $checkBoxValue ) {
mysql_query("INSERT INTO recipeequipment (recipeid, equipmentid, datetimeentered) VALUES('".$id."', '".$checkBoxValue."', '".$datetime."')");
}
The only thing that needs adding to this insert statement is the quantity, which is held in a similar fashion to the checkboxes, but in textboxes. like this:
<?php while($rowequipment = mysql_fetch_assoc($sqlequipment)) {
echo '<input type="checkbox" name="equipment[]" value="'.$rowequipment['equipmentid'].'"/>
<input type="text" name="count[]" id="count[]" size="3" value="" />'
.$rowequipment['description']."<br />";
}?>
The piece i need help with is the second input column. I need to put the values that correspond with the check boxes into the insert statement, but am unsure of how to do this.

Ignoring all the vunrabilities in your code for now, doing something like this should allow you to get a unique id and match the checkbox up to the input:
<?php while($rowequipment = mysql_fetch_assoc($sqlequipment)) {
echo '<input type="checkbox" name="equipment['.$rowequipment['equipmentid'].']" value="'.$rowequipment['equipmentid'].'"/>
<input type="text" name="count['.$rowequipment['equipmentid'].']" id="count-'.$rowequipment['equipmentid'].'" size="3" value="" />'
.$rowequipment['description']."<br />";
}?>
Then once that form is submitted you would simply loop through each checkbox by doing something like:
foreach ($_POST['equipment'] as $id => $checkboxValue) {
$textInputValue = $_POST['count'][$id];
// do something with the above value here
}
Although, I'm not quite sure why you're using checkboxes like this - is it so you ignore updating the rows that they don't check off or something?

Related

multiple values insertion of checkbox only last value is taking in database

I need to insert more than one values in checkbox but now it is seemed to be only the last value am entering is inserting to database.
this is my HTML code
<input id="option5" type="checkbox" name="product[]" value="<?php echo $result["software"];?>">
<label for="option5"><span><span></span></span><?php echo $result["software"];?></label>
and code for insertion is
$array = array($_POST['product']);
$value = implode(',', $array);
echo $value;
If you want to save multiple values in database then you need to create multiple checkboxes in html and then save the values with implode() method as below:-
<input id="option1" type="checkbox" name="product[]" value="value1">
<label for="option1">Value1</label>
<input id="option2" type="checkbox" name="product[]" value="value2">
<label for="option2">Value2</label>
<input id="option3" type="checkbox" name="product[]" value="value3">
<label for="option3">Value3</label>
now to store in database you can use implode() method.
$values=implode(",",$_POST['product']);
now store the $values in the database.
If i understand your problem you are looking for something like this:-
$array= array(
'0' => 123,
'1' => 456,
'2' => 789,
); // this is your post product array oryou want to get last value of that arrray
-----Or----
$array = $_POST['product']; // your post data after submission
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
echo $array[$key]; // 789
Hope it helps!
Your problem is likely:
You have multiple checkboxes.
And you want to insert all of them into database.
You need to loop your posted checkboxes.
Your problem is likely that you are not looping over the $_POST['product'], so, only, the last product is inserting into database.
So, your checkboxes:
<input id="option5" type="checkbox" name="product[]" value="<?php echo $result["software"];?>">
<label for="option5"><span><span></span></span><?php echo $result["software"];?></label>
The code for posted file:
if (! empty($_POST['product'])) {
foreach ($_POST['product'] as $product) {
// Here, you insert $product into database.
}
}

How to insert form values, some with same name, to multiple MySQL rows

I have been searching this for the last couple of hours and there are a few very similar questions and answers but none are quite working for my situation. What I'm trying to do is insert a list of songs set to the same value for two columns, one per row, and with a couple of options set via radio buttons. The latter is the reason why I can't just write all of the songs in a textarea and split them.
This is what the form looks like (obviously not fully designed)
There are only three there now while I get it working, in reality an unlimited amount may be added via javascript.
And the code:
<form action="" method="post">
<label>Session ID</label>
<input type="text" name="session-id"><br>
<label>Songs</label><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="song-key[]"><input type="checkbox" name="is-partial[]"><input type="checkbox" name="is-jam[]"><br>
<input type="text" name="update-date" value="<?php echo date(" Y-m-d H:i:s ");?>" hidden readonly><br>
<input type="submit" name="submit" value="Submit">
</form>
The desired result, assuming the ID has been set and a unique song entered for each of the them, and whatever variety on the radio buttons, would be three table rows. session-id and update-date would all be the same value, the rest would be unique based on entry.
This is what I currently have, but it only inserts the last of the three songs.
for ($i=0; $i < count($_POST['song-key']); $i++ ) {
$sessionkey = mysqli_real_escape_string($connection, $_POST["session-key"]);
$songkey = mysqli_real_escape_string($connection, $_POST["song-key"][$i]);
$partial = mysqli_real_escape_string($connection, isset($_POST['is-partial'][$i])) ? 1 : 0;
$jam = mysqli_real_escape_string($connection, isset($_POST['is-jam'][$i])) ? 1 : 0;
$updated = mysqli_real_escape_string($connection, $_POST["update-date"]);
$sql = "INSERT INTO session_songs (session_key, song_key, is_partial, is_jam, last_updated)
VALUES ('$sessionkey', '$songkey', '$partial', '$jam', '$updated')";
}
What do I need to change to ensure all three (or more) are entered?
If you alter your input names, you can get a more useful $_POST array.
<input type="text" name="songs[0][key]">
<input type="checkbox" name="songs[0][is-partial]">
<input type="checkbox" name="songs[0][is-jam]"><br>
<input type="text" name="songs[1][key]">
<input type="checkbox" name="songs[1][is-partial]">
<input type="checkbox" name="songs[1][is-jam]"><br>
<input type="text" name="songs[2][key]">
<input type="checkbox" name="songs[2][is-partial]">
<input type="checkbox" name="songs[2][is-jam]"><br>
With specified keys, the checkbox type inputs will match up properly with the text inputs, where they way you have it now, they will not*, because only checked checkboxes are submitted to PHP. (Try only checking "is-partial" in the second and "is-jam" in the third row, and then var_dump($_POST), and you'll see that they both have index 0.)
If your form is structured like that, you can insert your records using a foreach loop instead of a for loop.
foreach ($_POST['songs'] as $song) {
$key = $song['key'];
$partial = isset($song['is-partial']) ? 1 : 0;
$jam = isset($song['is-jam']) ? 1 : 0;
// do the insert inside the loop rather than just building the SQL
}
The reason you're currently only getting the last one is that you're defining the SQL string inside the loop, but without executing the statement in the loop, you'll only get the values from the last iteration of the loop. Move your query execution inside the loop and you should get all three rows.
*unless they are all checked

Adding checkboxes to table populated with mysql

I have been searching on this topic and the more I read the more confused I get. I hope you can help me on this.
My objective is to add checkboxes to a table in order to be able to delete the rows I select from that table. So my code til now is like this:
if ($arch = $pdo->prepare("SELECT name, age FROM table WHERE id = ?)) {
$arch ->execute(array($id));
$data = $arch->fetchAll();
echo '<div class="coolTable" ><table><tr><td>Name</td><td>Age</td><td>Check</td></tr>';
foreach ($data as $row){
echo '<tr>';
foreach ($row as $col){
$col=nl2br($col);
echo '<td>'.$col.'</td>';
}
echo '<td><input type="checkbox" name="checkbox" value="" id="checkbox"></td>';
echo '</tr>';
}
echo '</table></div>';
}
With this, I have all my checkboxes in place. But now, how can I submit the checkboxes with a Post so I can Delete the rows I checked?
I suppose I can use an array to name each checkbox? but don`t know how :-s
Thanks in advance for your help!
Change this line:
echo '<td><input type="checkbox" name="checkbox" value="" id="checkbox"></td>';
with
echo '<td><input type="checkbox" name="checkbox[]" value="" id="checkbox"></td>';
You can access every value of checked checkbox using this array $_POST['checkbox'] if you are using POST method or $_GET['checkbox'] for GET method.
PS: You should give your checkbox's a value.

PHP MYSQL checkbox checked

With this line of code, I add every selected checkbox's value into the database:
// ADD ALL TYPES TO PRODUCTIONLOG_TYPE TABLE
$x=1;
$values=array();
foreach($_POST['id'] as $x)
{
$AddToListQuery = "
INSERT INTO
productionlog_type
(productionlogid, typeid)
VALUES
('" . mysql_real_escape_string($_GET['productionlog']) . "', '". mysql_real_escape_string($x) ."')
";
mysql_query($AddToListQuery)or die("query fout " . mysql_error() );
}
I do this so I can echo out the checkbox checked if this is alreayd in the database.
The problem now is, when the user unchecks the checkbox and sends the form, it's not passing any value, right? So I can't delete it from the database...means that the checkbox remains checked.
What can I do about this?
If you know which of the checkboxes will be returned, you can filter out the ones you know something about and only the checkboxes that are not checked remain then.
You can also have a look at some processing of your page before you send the request, with JavaScript for example.
Or you can pass another hidden variable in your form that contains all the checkboxes you should receive in your PHP script. For example:
<input type="hidden" value="id_1,id_2,id_3" />
If you then receive this in your PHP script, you can see which of the ids (of the checkboxes) are expected.
EDIT
If you have:
<form method="POST">
<input type="hidden" name="checks" value="id1,id2" />
<input type="checkbox" name="id1" checked="checked" />
<input type="checkbox" name="id2" />
</form>
And then in PHP:
$arr = split(",", $_POST["checks"]);
foreach ($arr as $x){
if(isset($_POST[$x])){
// Add or update
}else{
// Remove
}
}
Note: I haven't tested the code, but it you just to get an idea on how it works

How to insert multiple textbox values in databse those are checked with checkbox with php?

Below is an explanation of exactly what I want
On the submission form I have multiple checkboxs. when users click on checkbox a textbox appears next to it, where user input text. I want to insert the value of texbox in array and insert it in database with PHP-MYSQL.
for example checkbox1 is index 0=>valueoftextbox, checkbox2 is index 1=>value of texbox2
How can I achieve this?
Serialize received $_POST.
<input type="checkbox" name="smth[]" value="One" />
<input type="checkbox" name="smth[]" value="Two" />
<input type="checkbox" name="smth[]" value="Three" />
<?php
if (isset($_POST)) {
$smth = serialize($_POST['smth']);
$query = mysql_query("INSERT INTO table VALUES ('$smth')") or die(mysql_error());
}
A few pointer to get you going:
1) From PHP use:
echo "<pre>";
print_r($_POST);
echo "</pre>";
That way you can see WHAT is posted from your client-form.
2) Note that an unchecked checkbox ISN'T posted at all.
So if you have following checkbox in your form named "wantsnewsletter".
Then check that from PHP like this:
if (isset($_POST["wantsnewsletter"])){
// It was checked.
} else {
// It wasn't checked
}
Futhermore you just have to think up some sensible naming and do the inserts into you DB.

Categories