Dynamic multidimensional post form - php

I have a form with a variable number of inputs. The inputs are inside the table and I need to get three values from them: the row, the column and the actual value inside the input.
Some may be populated some may not and I need all their values to update a mysql db (row and column to know what to update, value to know the new value to insert in the database).
This is my form (an example version of it):
<form method="post" action="">
<input name="data[111][222]" value="2" />
<input name="data[112][221]" value="0" />
<input name="data[113][223]" value="4" />
//goes on
<input name="data[324][435]" value="11" />
<input name="data[325][436]" value="" />
</form>
And that's as far as I go. How can I get the data from this form so I can do a simple update in my database that goes like this (for all the affected inputs):
update table set res="value_from_input" where row="row_value" and col="col_value"

<form method="post" action="">
<input name="data[111][222]" value="2" />
<input name="data[112][221]" value="0" />
<input name="data[113][223]" value="4" />
<input name="data[324][435]" value="11" />
<input name="data[325][436]" value="" />
<input type="submit" />
</form>
<?php
foreach ($_POST['data'] as $k1 => $v1)
{
foreach ($v1 as $k2 => $v2)
{
echo "<p>k1:".$k1."; k2: ".$k2."; value: ".$v2."</p>";
$query = "update table set res='$v2' where row='$k1' and col='$k2'";
mysql_query($query);
}
}
?>

foreach($_POST['data'] as $row => $row_array)
{
foreach($row_array as $col => $value)
{
// Sanitize all input data before entry
$mysql = "UPDATE table SET res='$value' WHERE row='$row' AND col='$col'";
}
}

Related

how to save multiple radio button in database using php without save button value

how to save multiple radio button in database using php without save button value.
my code :
$user_id = $_POST['user_id'];
foreach ( $_POST as $key => $val ) {
if ($key <> 'user_id') {
$bidder_interst_insert="INSERT INTO bidder_interest_list(id, bidder_id, bidder_interest_name) VALUES ('','$user_id','$val')";
$bidder_interst_insert_result = mysql_query($bidder_interst_insert);
if (mysql_affected_rows() > 0) {
$interest_list_success = "Thank you Successfull insert your interst list.";
$_SESSION['interest_list_success_msg'] = $interest_list_success;
} else {
$insert_error = "interst list Insert Error.";
$_SESSION['insert_error_msg'] = $insert_error;
header("location:interest_list.php");
}
}
}
This code work but database extra save in save button value how to solved this problem??
foreach ( $_POST as $key => $val ){
You are directly looping the $_POST, so the SAVE button value is also saving in the database. Take the values individually instead of looping the whole $_POST, then the SAVE button value won't be saved in the database.
And moreover you are using mysql functions which are deprecated, use mysqli or PDO.
EDIT::
Just take it the same way as u took user_id ==> $variablename = $_POST['fieldname'];
EDIT:::
Let me suppose i have a form like this
<form name="form1" id="form1" method="post" action="">
<input type="checkbox" name="products[]" value="A" checked="checked" />A <br />
<input type="checkbox" name="products[]" value="B" checked="checked" />B <br />
<input type="checkbox" name="products[]" value="C" checked="checked" />C <br />
<input type="checkbox" name="products[]" value="D" checked="checked" />D <br />
<input type="checkbox" name="products[]" value="E" checked="checked" />E <br />
<input type="checkbox" name="products[]" value="F" checked="checked" />F <br />
<input type="submit" name="save" id="save" value="Save" />
</form>
then i can do it like:
<?php
if(isset($_POST['save']))
{
$products = $_POST['products'];
foreach($products as $key => $value)
{
$qry = mysql_query("INSERT INTO tbl(product) VALUES('$value')");
}
}
?>
Try this
unset($_POST['name-of-save-button']);
$data = $_POST;
foreach ( $data as $key => $val ){//your code here}

Three page sequence of forms (checkboxes and text/number boxes) with foreach in php

I would like to pass variables through 3 pages. The 1st page asks the user which music genres they like (there will eventually be 20+ genres). The 2nd page asks the user to rank the genres they have selected and the 3rd page sorts and displays their ranking.
This first page asked the user to pick which genres they like:
<form id="genre" name="genre" method="post" action="musicsell.php">
<input type="checkbox" name="genre[]" value="Rap"/>Rap<br />
<input type="checkbox" name="genre[]" value="HipHop"/>HipHop<br />
<input type="checkbox" name="genre[]" value="RnB"/>RnB<br />
<input type="checkbox" name="genre[]" value="Rock"/>Rock<br />
<input type="checkbox" name="genre[]" value="Jazz"/>Jazz<br />
<p>
<input type="submit" value="Next">
<br />
</p>
</form>
This second asks them to rank (prioritize) the genres they have selected with 1 being the best:
<body>
The genre(s) you selected are: <br>
<form id="form1" name="form1" method="post" action="musicresults.php">
<?php
$name = $_POST['genre'];
if(isset($_POST['genre'])) {
foreach ($name as $genre){
?>
<input
type="number" required="required" id="<?php echo $genre ?>" name="music[<?php echo $genre ?>]" />
<?php echo $genre ?><br />
<?php
}
}
?>
<input type="submit" name="button" id="button" value="Submit" /></form>
</body>
The third and last page sorts and echos the results:
<?php
//Get the form results (which has been converted to an associative array) from the $_POST super global
$musicgenres = $_POST['music'];
//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );
//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
echo "$musicgenres is your $rank choice";
echo "<br>";
}
?>
It all works fine until the last page where I'm getting an "array to string conversion" error. Maybe I need to put in session variables but I'm not sure.
Any help would be appreciated.
It's exactly what the error says. It can't convert and array to a string.
Replace
echo "$musicgenres is your $rank choice";
with
echo "$music is your $rank choice";

Foreach input php and mysql

I know there are similar topics out there but haven't been able to find what I'm looking for. So what I need to do is target a specific input name and foreach loop only that input instead of the whole form.
HTML look something like below.
<form action"<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" name="table1" method="post">
<input name="something1" type="text" />
<input name="something2" type="text" />
<input name="something3" type="text" />
<input name="something4" type="text" />
<input name="something4" type="text" />
<input name="something4" type="text" />
<input name="button" type="submit" value="Add" />
</form>
So I wanna loop every "something4" and just ignore the rest. Is this possible?
Just to explain what I want to do with the value is for every "something4" I'm gonna add a field to my DB and the input the respective input value into that field.
something like below...
$i = 0;
foreach ($_POST as $something4 => $something4_value) {
$add = mysqli_query($connect, "ALTER TABLE 'table' ADD something4$i VARCHAR( 255 ) NOT NULL") or die (mysql_error());
$sql_update = mysqli_query($con, "UPDATE 'table' SET something4$i='$something_value' WHERE id='$id'") or die (mysql_error());
$i++;
}
I hope this make sense! Thank you! :)
Create each of the name="something4" into an array like this:
<input name="something4[]" type="text" />
Then you can do a
foreach($_POST['something4'] as $something4) {
}

How to check Checkbox not checked in foreach

I have html checkbox like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br />
<input type="checkbox" name="language[]" value="html" />HTML<br />
<input type="checkbox" name="language[]" value="java" />Java<br />
<input type="checkbox" name="language[]" value="c++" />C++<br />
<input type="submit" value="send" />
</form>
Now I want to detect the checkbox is not checked using this PHP
if($_POST)
{
if(empty($_POST['language']))
{
echo "bla";
}
else
{
foreach($_POST['language'] as $value)
{
echo 'Checked: '.$value.'
';
}
}
}
The output is always show the checbox checked.
My question is, how can I detect the checkbox is not checked?
Example I do not check PHP and Java.
You don't need to validate checkbox by checkbox in order to determine if they are checked or not, you won't get the unchecked checkboxes values at the time you send the form, so, sending the form like this:
<form action="" method="post">
<input type="checkbox" name="language[]" value="php" />PHP<br /> <!-- checked -->
<input type="checkbox" name="language[]" value="html" />HTML<br /><!-- checked -->
<input type="checkbox" name="language[]" value="java" />Java<br /><!-- unchecked -->
<input type="checkbox" name="language[]" value="c++" />C++<br /><!-- unchecked -->
<input type="submit" value="send" />
</form>
In your PHP, you will get an array as follows:
$_POST['languages'] = array("php", "html");
Now, lets say you have an array of all the values in order to check which ones you need to delete, and which ones you need to add, a rough code example would be as follows:
$allValues = array('php', 'html', 'java', 'c++');
$valuesForAdd = $_POST['language'];
$valuesForDeletion = array_diff($allValues, $valuesForAdd);
First you need the selectable items array in the backend:
$items = array('php','html','java','c++');
You have the posted (selected) languages array here:
$_POST['language']
Not selected languages array:
$not_selected_languages = array_diff($items,$_POST['language']);
I hope it helps.
Only 'checked' checkboxes get sent as parameters in a POST request.
If you want to know which aren't checked, you could have the value list stored on PHP side; then once you receive POST data - compare the array on PHP side with POST array.
$all_vals = array('php', 'c++', 'html', 'java');
$post_vals = $_POST['languages'];
foreach ($post_vals as $post_val)
if in_array($post_val, $all_vals)
$checkbox checked
else
$checkbox not checked
I assume this gives you enough liberty to do what you need.

PHP - To Insert data from checkbox forms into MYSQL

This is my first website that makes use of server-side technology.
And it's also my first delving into PHP working along side MYSQL.
I've been working and learning as I go.
I've created a basic management page for a database of product entries for a small Prom Dress business.
I've been working on the functionality of a form that the administrator can use to upload new entries to the database.
Some of these entries include:
Dress Name [text input]
Colour Availability
[check boxes]
I've run into trouble getting data from multiple check boxes from a HTML form into the database.
The choices in the check boxes should represent a boolean value (yes/no - 1/0)
Here's the form structure:
<form action="inventory_list.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Dress Name</td>
<td width="80%"><label>
<input name="Dress_name" type="text" id="Dress_name" size="64" />
</label>
</td>
</tr>
<tr>
<td align="right">Collections</td>
<td>
<label>
<select name="collections" id="collections">
<option value="other">Other</option>
<option value="hermione">Hermione</option>
<option value="jora">Jora</option>
<option value="manon">Manon</option>
</select>
</label></td>
</tr>
<tr>
<td align="right">Available Sizes</td>
<td>
<input type="checkbox" name="sizes[]" value="1" /> Sizes 2-6<br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 6-10 <br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 10-14<br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 14-18 <br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 18-22<br />
<input type="checkbox" name="sizes[]" value="1" /> Sizes 22-26 <br />
</td>
</tr>
<tr>
<td align="right">Dress Colours</td>
<td>
<input type="checkbox" name="colours[]" value="1" /> Pinks/Reds <br />
<input type="checkbox" name="colours[]" value="1" /> Blues/Greens <br />
<input type="checkbox" name="colours[]" value="1" /> Violet/Purple<br />
<input type="checkbox" name="colours[]" value="1" /> Yellow/Orange/Brown/Gold <br />
<input type="checkbox" name="colours[]" value="1" /> Black/White<br />
</td>
</tr>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Item Now" />
</label></td>
</tr>
</table>
</form>
And here is the PHP that I've built to deal with the form submitting data to the Database.
<?php
if (isset($_POST['Dress_name'])) {
$dress_name = mysql_real_escape_string($_POST['Dress_name']);
$collections = mysql_real_escape_string($_POST['collections']);
$sizesArray = $_POST['sizes'];
$coloursArray = $_POST['colours'];
foreach ($sizesArray as $key => $value)
{
echo "Key = $key || Value = $value<br />";
}
foreach ($coloursArray as $ckey => $cvalue)
{
echo "Key = $ckey || Value = $cvalue<br />";
}
//See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT ID FROM names WHERE Dress='$dress_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
//Add this product into the database now
$sql = mysql_query("INSERT INTO names (Dress)
VALUES('$dress_name')") or die (mysql_error());
$pid = mysql_insert_id();
//Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: inventory_list.php");
exit();
}
?>
As you can see, I've got as far as putting the data into an array. And now I've hit a bit of a brick wall, I can't seem to find an answer that makes sense anywhere.
How do I get the boolean values into correct columns in the database table?
Appreciate your time!
The first thing to know is that HTML checkboxes will return a result if checked, and will return nothing if unchecked. Therefore, it is important in your html to have your values increment:
<td align="right">Available Sizes</td>
<td>
<input type="checkbox" name="sizes[]" value="1" /> Sizes 2-6<br />
<input type="checkbox" name="sizes[]" value="2" /> Sizes 6-10 <br />
<input type="checkbox" name="sizes[]" value="3" /> Sizes 10-14<br />
<input type="checkbox" name="sizes[]" value="4" /> Sizes 14-18 <br />
<input type="checkbox" name="sizes[]" value="5" /> Sizes 18-22<br />
<input type="checkbox" name="sizes[]" value="6" /> Sizes 22-26 <br />
</td>
A fully normalized database schema would look something like this:
//Note that 'names' and 'collections are overloaded
//words and should be avoided
table BRANDS
id INT AUTOINCREMENT
collectionname VARCHAR
table SIZES
id INT AUTOINCREMENT
sizecategory VARCHAR //ie 'Sizes 18-22'
table COLOURS
id INT AUTOINCREMENT
colourname VARCHAR
table INVENTORY
id INT AUTOINCREMENT
brandid INT FOREIGN KEY (BRAND)
imageurl VARCHAR
table INVENTORY_SIZES
inventoryid INT FOREIGN KEY
sizeid FOREIGN KEY
table INVENTORY_COLOURS
inventoryid INT FOREIGN KEY
colourid FOREIGN KEY
Your BRAND, COLOURS and SIZES tables would need to be properly populated with your available options, and you could in theory dynamically load your page with data from those tables. The ids of each of the rows in those tables should end up as the values in your checkbox arrays.
//get your inputs
$query_values = array();
$query_values[':brandid'] = $dress_name = $_POST['Dress_name'];//note that you should change the value in your options here to the unique ids in your database.
$query_values[':sizeid'] = getSize($_POST[]);
$query_values[':colourid'] = getColour($_POST[]);
$query_values[':quantity'] = $_POST['quantity'];
$query_values[':imageurl'] = $_POST['imageurl'];
//Prepare and execute your sql
//Note that PDO will handle escaping problematic inputs.
$sql = "INSERT INTO INVENTORY ('brandid', 'imageurl') VALUES (:brandid, :sizeid, :colourid, :quantity, :imageurl)";
executeInsert($sql, $query_values);
$inventoryid = mysql_insert_id();
saveSizes($_POST['sizes'], $inventoryid);
saveColours($_POST['colours'], $inventoryid);
function saveSizes($size_array, $inventoryid) {
$sql = "INSERT INTO INVENTORY_SIZES ('inventoryid', 'sizeid') VALUES (:inventoryid, :sizeid)";
foreach ($size_array as $sizeid) {
$query_values = array();
$query_values[':inventoryid'] = $inventoryid;
$query_values[':sizeid'] = $sizeid;
executeInsert($sql, $query_values);
}
}
function saveColours($colour_array) {
$sql = "INSERT INTO INVENTORY_COLOURS ('inventoryid', 'colourid') VALUES (:inventoryid, :colourid)";
foreach ($size_array as $sizeid) {
$query_values = array();
$query_values[':inventoryid'] = $inventoryid;
$query_values[':colourid'] = $colourid;
executeInsert($sql, $query_values);
}
}
function executeInsert($sql, $query_values) {
$query = $conn->prepare($sql);
$query->execute($query_values);
}
Be sure to use PHP PDO to guard against security issues. I'm fairly sure some of that could be abstracted out/cleaned up better, but this should do the job. (Though I'm also fairly sure there are little bugs as I'm doing this cold and without testing.)
You need to place the insert statement in an 'else' statement after the 'if' which checks if the name already exists in the database.
I am not sure what exactly you are trying to do , since there is no statement that you are executing to put the 'checkbox' values in the database. You are echo-ing the sizes array to as an output for the administrator to see after he submits this form ,but you are not putting it in the database at all.
What will help is if you can share the database structure ( the column names) . If you don't have any columns for sizes 2-5 & other categories , add those & then change your insert statement to the following :
INSERT INTO names (Dress,Size2to5,Size5to10,Size10to15,Size15to20) VALUES('$dress_name','$size[0]','$size[1]','size[2]','size[3]')
Hope this helps. Do let us know if this works for you.

Categories