How to save checkbox array in database? - php

I have this form:
<tr>
<td><input type="hidden" name="ledlamps" value="LED lamps">LED lamps:</td>
<td><input class="field checkbox" type="checkbox" name="box[]" value="3mm"/><label class="choice">3mm</label></td>
<td><input class="field checkbox" type="checkbox" name="box[]" value="5mm"/><label class="choice">5mm</label></td>
<td><input class="field checkbox" type="checkbox" name="box[]" value="8mm"/><label class="choice">8mm</label></td>
<td><input class="field checkbox" type="checkbox" name="box[]" value="10mm"/><label class="choice">10mm</label></td>
<td><input class="field checkbox" type="checkbox" name="box[]" value="Ovals"/><label class="choice">Ovals</label></td>
<td><input class="field checkbox" type="checkbox" name="box[]" value="Assembly LEDs"/><label class="choice">Assembly LEDs</label></td>
</tr>
and this php code:
$box=$_POST['box'];
$ledlamps = $_POST['ledlamps'];
if ($box != 0) {
echo "$ledlamps: ";
while (list ($key,$val) = #each ($box)) {
$val1 = "$val, ";
echo "$val1";
}
}
If I output with echo it displays in the way I want it:
Led lamps: 3mm, 5mm, 8mm (if i tick the respective checkboxes)
But I want to store this in a mysql table field. How do I do that?
Thanks for your help!

You can use implode() to join the $box array in to one string as follows:
$box=$_POST['box'];
$ledlamps = $_POST['ledlamps'];
$str = $ledlamps . ": " . implode(", ", $box);
Then $str should contain "Led lamps: 3mm, 5mm, 8mm" (depending on the fields you've checked).
This field can then be inserted in to whatever mysql column you need (assuming here that your query is properly escaped and input validated before attempting a db query..).
This way of storing the data will likely make it quite tricky to query the data again should you wish to pull it out again, so while it should suffice for simple printing to screen of something like a product history, you may be better investigating whether your db table structure could be made more accommodating. So if we assumed this was for a stock control system, something like:
category table:
- category_id
- category_name (LED lamps..)
stock table:
- item_id
- category_id (id for LED lamps..)
- item_description (3mm lamp, etc)
stock_selection table:
- transaction_id
- user_id
- date
stock_transaction table:
- transaction_id
- item_id
- change (number of items added/removed)
So once you receive back the checkboxes from your form, you create a new stock_selection record for the logged-in user. You then use the id from this new record and make 1 entry per checkbox in the stock_transaction table.
This would allow you in future to query your database to keep track of things like how many items have been taken out (or re-added, etc), who took them, etc, and may ultimately be a more future-proof approach, depending on your overall architecture.

Either store them in the database serialized as suggested by #Sarfraz, or comma separated, or in a separate table, joined with the primary table.

You could either:
$boxes = implode(",", $_POST['boxes']);
$id = intval($_GET['id']);
$sql = sprintf("UPDATE table SET box=%s WHERE id=%d", $boxes, $id);
$res = mysql_query($sql);
This would store box values in a comma-separated array, which you could then explode() when retrieving from the database.
Alternatively, you could set up a separate table if you want to go the proper route. That way you could have a many-to-one relationship, where one object (let's say car) can have many lamps.
Table: cars
- ID
- Name
Table: cars_lamps
- Car_ID
- Lamp_ID
Table: Lamps
- ID
- Name
I hope that makes sense.

Related

mysql Update Statement depending on number of checkbox checked

Problem statement:
I have a form with multiple checkbox Fields, i have validated it so
user can select maximum 9 checkbox and atleast 1 with jquery.
I collect the Form checked values using Post method.
i have mysql table with 12 columns.
first 3 columns are "id", "rollnum", "selectStatus"
Through session variables created during Login, i get roll number of student. So i can Run Update Query on particular row.
Question: How do i Update those 9 subject columns according to user checked inputs. Note : i stored those checked input field values in an array.
Code
<form action="index.php" id="form-3" method="post">
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="ucs303">UCS303 Operating Systems
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="ucs406">UCS406 Data Structures and Algorithms
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec401">UEC401 Analog Communication Systems
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec612">UEC612 Digital System Design
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec307">UEC307 Electromagnetic Field Theory & Trans Lines
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec502">UEC502 Digital Signal Processing
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="uec510">UEC510 Computer Architecture
<button type="submit" name="year-3-submit">Submit Selection</button>
</form>
<?php
if(isset($_POST['year-3-submit'])){
if(!empty($_POST['year-3-checkbox'])){
$subjectCheckList = array();
$subjectCheckList = $_POST['year-3-checkbox'];
}
}
?>
It depends on user how many checkbox is selected.
I donot know how to write UPDATE sql query which updates values of number of columns == size of array.
for example:
User 1 has selected 3 checkbox and submitted form, we have array of size 3 and UPDATE 3 columns of table.
User 1 has selected 6 checkbox and submitted form, we have array of size 6 and UPDATE 6 columns of table.
I donot want to write 9 switch case statements for all possible sizes
of array. Any idea? please?
Based on OP's comments, you can make the code generic as follows:
// Check if atleast one subject has been selected
$selectedSubjects = array_filter($subjectCheckList);
// If no subject selected
if (empty($selectedSubjects)) {
$sql = "UPDATE subjectmaster
SET substatus = 0
WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
} else {
// Initialize the sql string
$sql = "UPDATE subjectmaster
SET substatus = 1 ";
$i = 1;
foreach ($subjectCheckList as $subject) {
$sql .= ", sub" . $i . " = '" . mysqli_real_escape_string($subject) . "' ";
}
$sql .= " WHERE rollno = '" . mysqli_real_escape_string($rollnumber) . "'";
}
Also, note the use of mysqli_real_escape_string. It helps in preventing SQL injection. For better ways to prevent SQL injection, you may check How can I prevent SQL injection in PHP?
Well, 1st of all it is not clear what should be the default valued for each column.
Since your MySQL columns are set by numbers (sub1, sub2, etc) then your form should represent them accordingly, with the proper value. for example:
<input class="form-check-input" name="year-3-checkbox[]" type="checkbox" value="1">
This way, you can loop easily and update the table (I assume the sub columns are TINYINT(1) DEFAULT NULL) :
<?php
if(isset($_POST['year-3-submit'])){
if(!empty($_POST['year-3-checkbox'])){
$subjectCheckList = array();
$query = "UPDATE table SET ";
foreach ($_POST['year-3-checkbox'] as $key => $value) {
$query .= " sub" . $value . " = 1, "
}
$query = substr($query, 0, -1);
}
}
?>
Hope this helps
Guy
You can also use array_filter, array_combine and array_slice.
<?php
$subs = [':sub1',
':sub2',
':sub3',
':sub4',
':sub5',
':sub6',
':sub7',
':sub8',
':sub9'
];
// use $dataFromForm = array_filter($_POST['year-3-checkbox'])
$dataFromForm = ['11111',
'222222',
'3333333'];
$dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '*******');
$sql = 'UPDATE test SET sub1 = :sub1, sub2 = :sub2, sub3 = :sub3, sub4 = :sub4, sub5 = :sub5, sub6 = :sub6, sub7 = :sub7, sub8 = :sub8, sub9 = :sub9';
$sth = $dbh->prepare($sql);
$sth->execute(array_combine(array_slice($subs, 0, count($dataFromForm), $dataFromForm)));

Retrieving and inserting multiple entries in MySQL/PHP

I'm trying to create a form that retrieves data from a database and then allows me to add data to one column for multiple entries.
Every entry has an ID, a lot of other fields, and a category. I am trying to add these categories for every ID in the database using one form.
I came up with the solution below, but (of course)this only inserts the LAST entry in the form, because the variable ID is changed with every new row.
The form I have now shows me what I want to see, but it does not save it the way I need it to.
The question is, (how) can I make a form that has all entries in the database with a dropdown menu next to it,
lets me select the right category from the dropdown, and save it to the database?
The form:
$result = mysqli_query($con,"SELECT * FROM aw");
while($row = mysqli_fetch_array($result))
{
echo '<tr><td><input type="hidden" name="ID" value="'.$row[ID].'."> '.$row[ID].'</td><td>';
echo '
<select name="cat" onchange="this.form.submit()">
<option value="C1">category1</option>
<option value="C2"">category2</option>
</select></td></tr>
';
}
?>
<tr><td><input type="submit" title="SAVE" ></td></tr>
</form>
The insert.php
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$_POST[ID]','$_POST[cat]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
I changed my code according to Tom's answer and I now have the following:
This does print the values like they should be, but it still saves only the last entry into the database. I'm sure I must be missing something here..
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$n','$category[$key]')";
print "The id is ".$n.", category is ".$category[$key]."<br>";
}
First of all, use PDO::Mysql, the SQL functions you are using are a bit deprecated and do not focus much on security. At the moment your code is vulnerable to SQL injections and your output is sensitive to XSS attacks (always sanitize output).
I was wrong, MySQL is deprecated but MySQLi is not! I do prefer using PDO::Mysql because of the range of databases it supports (MySQLi only supports a MySQL database, PDO::Mysql supports many more)
Now to your original question, you can create a sort of array. By making name="ID" to name="ID[]" and name="cat" to name="cat[]".
Now you can do
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
print "The id is ".$n.", category is ".$category[$key];
}
The problem is your using the name elements regardless of how many rows..
So name="ID" & name="cat" needs to change on each row or have an array type
you could use something like name="ID[]" as this would append/ create an array to $_POST['ID']... but you still would want to change your SQL query to handle each of these.
EDIT
If i understand, you want to be able to identify a row from the table so you can use that in the database?? One way todo this is when creating the table.. Give the TR a id/name attribute that is the row id from the database.
Then can simply know by checking that if your using the select menu from row #4, you check the id/name attribute of the current row and you have your database id.
<tr id='my_row_1'>
<td class='colName'>John</td>
<td class='colPhone'>1111</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_2'>
<td class='colName'>Bill</td>
<td class='colPhone'>2222</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_3'>
<td class='colName'>Roger</td>
<td class='colPhone'>3333</td>
<td class='colOther'>....</td>
</tr>
With something like the above, Say i had a button in on of the columns... When i click on that button.. all i have todo is find the parent TR and get its id value.... Then explode it by "_" and get the last piece to have the id..
So your PHP would generate the id easily... Also, using a form would not be the best case here.. Using multiple forms within a table is... wasteful... sort of ..
I would suggest more so, having a button that simple calls a js function which will then post/ajax/jquery what you need from that row.
--- Trying to understand exactly what you need??

how to make 2 values textfield inserted into one column in database in php?

i have a problem..
what i want is..i have a form with 2 textfield. i want the value after we insert data into it..the data will insert into database in one column..but how to do it?sory for my bad english..:'(
<td bgcolor="#A4DDED"> <strong>DL</strong>
<input name="NF1" type="text" size="10" id="NF1" />
<strong> / </strong>
<label>
<input name="Y2" type="text" id="Y2" size="10" />
</label></td>
i have 2 textfield with difference name or id.. how to make the value insert into database in one column?
..we will insert some value to it and it will insert into database
|DL____/_____|
example: |DL 2909/2034| <--the data will inserted after we insert at form page*
you need to concatenate the two input fields and insert into the single column
$concat = $variable1 . $variable2;
then insert the concat variable in one column
Just add it together in a string and then add the string to the database.
$concat = '|DL ' . $_POST['NF1'] . '/'. $_POST['Y2'] . '|';
if NF1 = 2909 and Y2 = 2034 the output will be:
|DL 2909/2034|

Deleting from table if check box unticked

This is probably an easy one but I am stuck. I have a form with checkboxes that show employees and there skills, these are taken from a table with a many to many relationship.
The below code works for updating the records but I am unsure on how to delete records if the checkbox is un-checked
$emp=$_POST['emp'];
if(isset($_POST['chk1'])){
$checkbox=$_POST['chk1'];
$arr_num=count($checkbox);
$i=0;
while ($i < $arr_num)
{
$qry = "INSERT IGNORE INTO skillsets (skill_id, empr_id )VALUES(?, ?)";
$stmt = $mysqli->prepare($qry);
$stmt->bind_param('ii', $checkbox[$i], $emp);
$stmt->execute();
$i++;
}
}
else .... delete from .....
I am not sure of the syntax for the else, can someone help me out?
You can define hidden inputs for every checkbox (before it) with the same name. Eg.
<input type="hidden" name="items[1]" value="no" />
<input type="checkbox" name="items[1]" value="yes" />
1 is your item ID.
And now if checkbox is checked then its value will be send. In other case, value from hidden field will be send to your server. With this data you can iterate through items array, get ID from index and check value to know if it's checked or not.

how do you store multiple rows and column array in mysql

I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}

Categories