Getting data from checkbox from multi-dimentional array - php

I have a form which consist of a multi-D array. It has both checkbox and text. So i would like to use both values to enter them in database. I could not figure out how to use them. Any help would be much appreciated. Here is my code ;
$clothes = array(
"For_Man"=>array("Suit", "Tie"),
"For_Woman"=>array("Skirt","Bra")
);
echo '<form action="" method="POST">';
foreach ($clothes as $cloth => $task) {
echo "<strong>{$cloth}</strong> <br />";
foreach ($task as $type){
echo "<input type=\"checkbox\" name=\"box[]\" value=\"{$type}\" />\r
{$type} <input type=\"textbox\" name=\"note[]\" size=\"2\" /><hr />\r";
}
}
echo "<input type=\"Submit\" name=\"submit\" value=\"Submit\" />\r
</form>";
if(isset($_POST['box'])){
if(isset($_POST['note'])){
$note = $_POST['note'];
}
$box = $_POST['box'];
}
So user can select the item and enter the amount they want so i can use it to enter database like
new_order = mysql_query("INSERT INTO orders(cloth_name, amount,... ) VALUES ('$box', '$note', ...........");

I really don't understand you, do you want to save each product of your array in the database? if it is the case you can put it in another table you know,
=products=
Id_Product
name
=Orders
Id_Order
...
=Products_Orders
Id_PO
Id_Product
Id_Order
amount
note
instead of putting the information in a unique table.

Related

Updating data in MySQL database based on checked dynamic checkboxes in the table

I'm sorry about my question, but I'm starting with PHP and I want to ask you for a help with my problem.
In my web application I work with a table, which has a dynamic count of rows based on the number of rows in a source table in MySQL database. In the application should be a checkbox in each row of the table. After clicking on the submitt button there should be update of records in the source table and it should be update just of these records where the checkboxes were checked.
The table in the application looks simillar like in the picture.
The primary key in the source table is in the column NUMBER. As a first try I simulated that after clicking on submitt button there will be shown the msgbox with the values from the column NUMBER for the rows, where the checkboxes were checked.
<html>
<head>
<title>APLICATIONa</title>
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += " " + row.cells[1].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
</head>
<body>
<?php
$values = mysql_query("SELECT * FROM table_03_2020");
echo "<br><form action='main.php' method='POST'>";
echo "<input type='submit' name='button' value='Get Selected' class='btn btn-primary' onclick='GetSelected()' />";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
echo "<td><input type='checkbox' name='cbox[]' ></td>";
echo "<td><font color='red'>".$zaznam["number"]."</font></td>";
echo "<td>".$zaznam["name"]."</td>";
echo "</tr>";
endwhile;
echo "</table><br>";
echo "</form>";
?>
</body>
</html>
The msgbox is just an illustration. Instead of msgbox, I need that after clicking on the submit button, there should be an update for these records in the source table, where the checkboxes were selected (so of these records, which are now shown in the msgbox). So I need something like:
"UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
There'll be also a second submit button and after clicking on it, there should be another different update. So after clicking on the second button, I need something like:
"UPDATE table_03_2020 SET column1 = 'ab' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
I'm sorry if my question is not so clear, but I'd really appreciate any help.
Thank you very much.
Add key values with the number to the cbox form variable:
echo "<td><input type='checkbox' name='cbox[" .$zaznam["number"]. "]' ></td>";
Then use the following PHP to get the number list.
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
The addslashes function is for SQL Injection protection.
This will create a list with comma separated numbers.
Than, you can insert it in the the SQL query.
UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('. $checked_list .')
If you assign a value to the checkboxes, like this:
<input type='checkbox' name='cbox[]' value='{$zaznam["number"]}' >
When the form is submitted the cbox variable will contain an array of these numbers, which means that you can process them like this:
<?php
include 'db.php'; #your database connection!!!
$sql='update table_03_2020 set `column1`="XY" where `column2` in ( ? )';
$stmt=$db->prepare( $sql );
$ids=implode(',',$_POST['cbox']);
$stmt->bind_param('s',$ids);
$stmt->execute();
?>
Note that the above has not been tested so there might be errors but I hope it'll give the idea.
Thank you, I tried to improve the part of the code to:
echo "<input type='submit' name='buttonupdate' value='Get Selected' >";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
if ($_POST["buttonupdate"]) {
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
}
echo "<td><input type='checkbox' name='cbox[" .$zaznam["cflot"]. "]' ></td>";
It didn't work, there was no update. Did I edited the code incorrectly?
Actually I forgot to mention the second button, so I edited my first post. Would it be possible to distinguish between the first and the second button? Thank you very much for any help.

PHP MySQL save a row id to a database based on user checkbox

I am attempting to get the sql row that a user checks with a checkbox and post the id to a script that will save the users selected rows to a db so they can pull "saved" rows at a later data.
Below is my code -- the issue is when I post the checkbox value it is appearing as "1" and I am not sure why this is happening. All checkbox values are appearing as "1".
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', '');
mysql_select_db('msl_data');
$query = "INSERT INTO searches (ID, school, type) VALUES('$current_user->ID', '$school', '1')";
mysql_query($query);
$search = mysql_query("SELECT * FROM `data` WHERE `school` LIKE '%$school%'");
$count=mysql_num_rows($search);
if ($count==0) {
echo 'Sorry your search for'; echo " $school "; echo 'returned no results. Please try again.';
}
else {
$fields_num1 = mysql_num_fields($search);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_array($search)){
foreach($row as $rowarray)
while($row1 = mysql_fetch_row($search)){
echo "<tr>";
echo "<td><input type='checkbox' value='$rowarray' name='cell'></td>";
// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
echo "<td>$cell1</td>";
echo "</tr>\n";
}
}
}
echo "<input type='submit' value='SAVE'>";
mysql_close(); //Make sure to close out the database connection
Your checkboxes should be as array as they are multiple. The reason why you get them all as 1 as they override each other.
<form method='post' id='form' action='page.php'>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
<input type='submit'>
</form>
<?php
if(isset($_POST['submit']){
$v = $_POST['checkboxvar'];
foreach ($v as $key=>$value) {
echo "Checkbox: ".$value."<br />";
}
}
?>
TBH, this thing was a mess. The base of your problem was a) only having a single named element (as the other answer pointed out) and b) trying to give it an array as a value. But even after fixing that this was never going to work.
You had your database results inside four separate loops, I don't know what the thinking was there. As well, if you presented me with this web page, I could easily erase your entire database with a single click.
Here's what it looks like after 5 minutes of work. I'd still not call this a reasonable script, but hopefully it will give you something to learn from. You need to make a priority to learn about preventing SQL injection, and the first way to do this is to stop using a database engine that's been unsupported for 5 years. PDO is the easiest alternative as it's built into PHP for nearly a decade now. It provides convenient methods for dumping a result set into an array easily.
<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$db = new PDO("mysql:host=198.71.225.63;dbname=msl_data", "newmslsuper", "");
$stmt = $db->prepare("INSERT INTO searches (ID, school, type) VALUES(?,?,?)";
$stmt->execute(array($current_user->ID, $school, 1));
$stmt = $db->prepare("SELECT * FROM `data` WHERE `school` LIKE ?");
$stmt->execute(array("%$school%"));
// put it in an array. presto!
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) === 0) {
echo "Sorry your search for '$school' returned no results. Please try again.";
}
else {
$fields = array_keys($result[0]);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// assume "id" field is first
unset($fields[0]);
// printing table headers
foreach($fields as $field) {
echo "<th>$key</th>";
}
echo "</tr>\n";
// printing table rows
// just one loop
foreach($result as $row) {
echo "<tr>";
// assume the column is named "id"
echo "<td><input type='checkbox' value='$row[id]' name='cell[]'></td>";
unset($row["id"]);
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
echo "<input type='submit' value='SAVE'>";
echo "</form>";
}
?>

HTML form with checkbox and number types submission with PHP?

For learning purposes, I'm doing this website where user can select some items and the number of units he wants, let's say it's this simplest shopping app.
So, I read from database the existing items in catalog:
$queryResult=$mySQL->query("SELECT nombre, precio, id FROM productos");
Then I print the list of products:
$queryResult=$mySQL->query("SELECT nombre, precio, id_producto FROM productos");
echo "<form action=\"checkout.php\" method=\"POST\">";
while($datos=$mySQL->fetch_array($queryResult))
{
$nombre=$datos['nombre'];
$id_producto=$datos['id_producto'];
$precio=$datos['precio'];
echo "<h1>$nombre</h1>";
echo "<input type=\"checkbox\" name=\"$id_producto\" value=\"on\"> Cantidad: <input type=\"number\" name=\"$id_producto"."Number\""." min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
echo "<h3>Precio: $precio</h3><br>";
}
echo "<br>";
echo "<input type=\"submit\" class=\"button\" value=\"Comprar\">";
echo "</form>";
They get as value the ones from $id_producto, in the case of the number type inputs I concatenate "Number" so they dont get the same name.
After submission, I'm trying to do something like:
foreach($_POST as $post_key => $post_value){
if ($post_value=="on") {
$var1 = $_POST['.$post_key."Number".'];
}
}
So if a checkbox was selected I check for its corresponding numeric value.
Is it OK to perform another $_POST['somevariable'] inside that loop?
How can I concatenate that argument inside the square brackets?
You don't need the single quotes, that's for when the key is a constant string. Since your key is an expression, just put that expression inside the brackets:
if ($post_value=="on") {
$var1 = $_POST[$post_key."Number"];
}
A better way to do this is to post the inputs as arrays:
echo "<input type=\"checkbox\" name=\"producto[]\" value=\"$id_producto\"> Cantidad: <input type=\"number\" name=\"Number[$id_producto]\" min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
Then you can use the loop:
foreach ($_POST['producto'] as $post_value) {
$var1 = $_POST['Number'][$post_value];
}

Submit of selected on checkbox items?

I print this form in a web page with php:
<?php
include("connectDB.php");
$mySQL=new MySQL();
$queryResult=$mySQL->query("SELECT nombre, precio, id_producto FROM productos");
echo "<form action= 'checkout.php'> method=''POST'";
while($datos=$mySQL->fetch_array($queryResult))
{
$n = 1;
$nombre=$datos['nombre'];
$id_producto=$datos['id_producto'];
$precio=$datos['precio'];
echo "<h1>$nombre</h1>";
echo "<input type=\"checkbox\" name=\"$id_producto\" value=\"$nombre\"> Cantidad: <input type=\"number\" name=\"points\" min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
echo "<h3> Precio: $precio<br>";
}
echo "<br>";
echo "<input type=\"submit\" class=\"button\" value=\"Comprar\">";
echo "</form>";
?>
So it displays a list (which is a form within) of items which can be selected or checked, on submit, I want to do the $_POST[''] of only the checked items, how could I solve this?
When such checkboxes are printed, only those values which were checked are submitted.
If i understood you correctly you wanted to retrieve those that got posted, which you can follow with this simple method
foreach($_POST as $post_key => $post_value){
//Check that the particular input is int and numeric, since i believe the name is the id
if(is_numeric($post_key) && is_int($post_key){
//Here goes your code, $post_key is the id and $post_value is the $nombre
//Although i admit that i have no idea what nombre is since it is in another language. Forgive me if id_producto is not numeric and unique.
}
}

Creating a list of checkboxes with values from a php array as its label

I want to create a list of checkboxes with values from a php array as its label. I want it to look like
Here is the list of students whose schedules are saved:
[checkbox] Robb
[checkbox] Catelyn
[checkbox] Lady Stoneheart
but my code does not work.
Here's my code:
<?php
$students = $_SESSION['students'];
echo "Here is the list of students whose schedules are saved:<br/><br/>";
echo "<form action='checkbox-form.php' method='post'>
Load student?<br/>";
foreach ($students as $stud) {
echo "<br/><input type='checkbox' name=" . $stud . " value='load' />";
}
echo "<br/><br/><input type='submit' name='formSubmit' value='Submit' />
</form>";
?>
The array is not the problem because it contains the proper values when I print it through foreach.
It might be easier to do it this way:
On the form:
foreach ($students as $stud) {
echo "<br/><input type='checkbox' name=\"students[]\" value='$stud' />$stud<br>";
}
On the handler to see what it's passing:
print_r($_POST);
If all of the "value" fields are "load", which in this case they are, nothing can happen because your PHP won't see anything different value-wise.
You should set the name value of all of these checkboxes to the same thing, and set the value to the student's name (though that's bad design- you should be setting the value to the numeric DB id that represents the student- what if you have students with the same name?)
So:
for($i = 0; i < count($students); $i++) {
$s = $students[$i];
echo "<br/><input type='checkbox' name="students[]" value='$s' />";
}
In this case name="students[]" is the students ARRAY which you can access via $_POST['students'] as an array.
It looks like you've confused the "name" attribute for the label. A few notes:
"name" is used as the name of the parameter passed to the backend
"value" is the value that will be assigned to that parameter if the checkbox is checked
So the line in your foreach should look more like:
echo '<br /><input type="checkbox" name="students[]" value="'.$stud.'" />'.$stud;
If Robb and Catelyn are checked you will get the below in the $_POST['students'] variable server side:
Array
(
[0] => Robb
[1] => Catelyn
)
foreach($students as $student){
echo "<br/><input type='checkbox' name=" . $student . " value=" . $student . " />";
echo "<label for name=" . $student . ">" . $student . "</label>";
}

Categories