Looping through $_POST - php

I have a MySQL database with the table "chapters". The table "chapters" has three columns: (1) id, (2) name, (3) password.
I am using PHP to dynamically output the data from "chapters" into text boxes. The result looks something like this:
<form name="current_chapters" method="post" action="UpdateChapters.php">
<input type = 'text' name='id' value='{$row['id']}'>
<input type = 'text' name='name' value='{$row['name']}'>
<input type = 'password' name='password' value='New Password'>
<input type = 'submit'>
</form>
Note that this page is used to reset (not display) passwords, hence the "New Password" default value.
I am looking for the best way to loop through all of that $_POST data and then update the original "chapters" table that this data originally came from.
I tried playing around with looping through $_POST via foreach and changing the input names to "id[]", "name[]", and "password[]", but it doesn't seem to be the most elegant approach, especially with the id part...you end up with things like id[0] = 133, which just seems messy.
Any recommendations on how to go about doing this?
Thanks in advance!

You can pass in structured data using $_POST. Which eases handling multiple fields of the same type:
<input name="book[12][name]" value="name of book 12">
<input name="book[12][password]" value="password for book12">
<input name="book[99][name]" value="name of book 99">
<input name="book[99][password]" value="password for book99">
Which will create data structure in $_POST like the following:
[book] => Array
(
[12] => Array
(
[name] => name of book 12
[password] => password for book 12
)
[99] => Array
(
[name] => name of book 99
[password] => password for book 99
)
)
Which you can then iterate as follows:
foreach ($_POST['book'] as $book_id => $book) {
// Watch out for SQL injection
$sql = "UPDATE book SET name = '{$book['name']}', password = '{$book['password']}' WHERE id = $book_id";
}

Related

How to insert array data to mysql table

I have two tables called op_group and options .These two tables are filled by array values. For example, I want to insert pizza details into my tables.
It look like this:
Cheese pizza and Sausage pizza will get inserted into the op_group table.
Other data will get inserted into the options table. These options should be inserted based on the relevant foreign key op_group id.
This is what i have tried. All details are inserted but not for the relevant op_group.
$opg_name=$_POST['opg_name'];
$price=$_POST['price'];
$itemCountz = count($opg_name);
$itemValues=0;
$queryValue1 = "";
for($i=0; $i<$itemCountz; $i++) {
$itemValues++;
if($queryValue1!="") {
$queryValue1 .= ",";
}
$queryValue1 = "INSERT INTO op_group
(opg_id,ml_id,cat_id,res_id,res_name,op_grp)
VALUES(NULL,'".$ml_id."','".$cat_id."','".$res_id."','".$res_name."','".$_POST["opg_name"][$i]."')";
$result1= mysql_query($queryValue1)or die(mysql_error());
$query6= "SELECT * FROM op_group ORDER BY opg_id DESC LIMIT 1" ;
$result6= mysql_query($query6);
while($row6 = mysql_fetch_assoc($result6)){
$opg_id=$row6['opg_id'];
}
$itemCount2 = count($price);
$itemValues1 = 0;
$queryValue2 = "";
for($j=0;$j<$itemCount2;$j++) {
if(!empty($_POST["op_name"][$j])||!empty($_POST["price"][$j])) {
$itemValues1++;
if($queryValue2!="") {
$queryValue2 .= ",";
}
$queryValue2 = "INSERT INTO options (op_id,opg_id,ml_id,cat_id,res_id,res_name,opt,price) VALUES (NULL,'".$opg_id."','".$ml_id."','".$cat_id."','".$res_id."','".$res_name."','".$_POST["op_name"][$j]."','".$_POST["price"][$j]."')";
}
}
$result2=mysql_query($queryValue2)or die(mysql_error());
}
This code give result like this
options table inserted data looks like this
how to solve this?
The reason why you are seeing options being duplicated for each option group is because your $queryValue2 is being repeatedly executed for each option group inside your outer most for($i = 0; $i < $itemCountz; $i++) loop.
As it stands, your current way of organizing the $_POST inputs are quite messy (and so are your duplicated row attributes). I will suggest you group your HTML inputs fields by each option group. You can try something like this:
<div>
<input type="text" id="first_order" name="orders[0][name]" /><br />
<input type="text" name="orders[0][options][0][price]" /><br />
<input type="text" name="orders[0][options][0][size]" /><br />
<input type="text" name="orders[0][options][1][price]" /><br />
<input type="text" name="orders[0][options][1][size]" /><br />
</div>
<div>
<input type="text" id="second_order" name="orders[1][name]" /><br />
<input type="text" name="orders[1][options][0][price]" /><br />
<input type="text" name="orders[1][options][0][size]" /><br />
<input type="text" name="orders[1][options][1][price]" /><br />
<input type="text" name="orders[1][options][1][size]" /><br />
</div>
Notice how I use the HTML name attribute to group the food options by the food. Then if you submit this form, you will see that the $_POST array appears to look something like this:
Array
(
[orders] => Array
(
[0] => Array
(
[name] => "Cheese Pizza"
[options] => [0] => Array([size] => "8'"
[price] => "12")
[1] => Array([size] => "12'"
[price] => "14")
)
[1] => Array
(
[name] => "Sausage Pizza"
[options] => [0] => Array([size] => "8'"
[price] => "13")
[1] => Array([size] => "12'"
[price] => "16")
)
)
)
Now you can tidy up your backend PHP codes with something like this:
foreach ($_POST['orders'] as $orders) {
// .. some codes
foreach($orders as $order) {
// .. add codes to insert into op_groups where $order['name'] will give you the pizza name
foreach($order['options'] as $details) {
// .. add codes to insert into options where $details['size'] and $details['price'] will give you the corresponding values
}
}
}
Also, you can use mysqli.insert-id to get the row ID of the last inserted row. Then you can get rid of that silly $query6 and its while loop.
Of course, don't forget to sanitize your $_POST inputs before using them!
I am getting a bit tired, if there are mistakes, I will fix them up tomorrow. Hope it helps!

How to iterate through $_POST to update multiple recordsets in DB via PDO

I'm new to PDO and associative arrays but am making good progress. I've set up this code to save a html form to a single recordset:
$str_sql = "UPDATE tbl_benutzer SET ";
foreach($_POST as $key=>$value){
if($key=='id'){continue;}
$str_sql .= $key." = :".$key.", ";
}
$str_sql = substr($str_sql,0,-2)." WHERE id = :id";
///////SAVE DATA TO DB///////
$stmt = $conn->prepare($str_sql);
$stmt->execute($_POST);
Now I want to adapt the same code to save the contents of a html form to multiple recordsets. Here's the HTML:
<input name="id[]" value="1">
<input name="tarif[]" value="A">
<input name="mitgliedschaft[]" value="X">
<input name="gebuehr[]" value="100">
<input name="id[]" value="2">
<input name="tarif[]" value="B">
<input name="mitgliedschaft[]" value="Y">
<input name="gebuehr[]" value="200">
<input name="id[]" value="3">
<input name="tarif[]" value="C">
<input name="mitgliedschaft[]" value="Z">
<input name="gebuehr[]" value="300">
And here's the $_POST array:
Array ( [id] => Array ( [0] => 1 [1] => 2 [2] => 3 )
[tarif] => Array ( [0] => A [1] => B [2] => C )
[mitgliedschaft] => Array ( [0] => X [1] => Y [2] => Z )
[gebuehr] => Array ( [0] => 100 [1] => 200 [2] => 300 ) )
This is what I've tried so far but my head's just not getting around it!:
$str_sql = "UPDATE tbl_stamm_tarif SET ";
foreach($_POST as $key=>$value){
if($key=='id'){continue;}
$str_sql .= $key." = :".$key.", ";
}
$str_sql = substr($str_sql,0,-2)." WHERE id = :id";
echo $str_sql;
///////SAVE DATEN TO DB///////
$stmt = $conn->prepare($str_sql);
foreach($_POST as $key=>$value){
foreach($value as $key2=>$value2){
$stmt->execute(array($key=>$value2));
}
}
Thanks in advance for any help!
I'd consider changing your HTML structure to something like:
<input name="**model_name**[**id1**][tarif]" value="A">
<input name="**model_name**[**id1**][mitgliedschaft]" value="X">
<input name="**model_name**[**id1**][gebuehr]" value="100">
<input name="**model_name**[**id2**][tarif]" value="B">
<input name="**model_name**[**id2**][mitgliedschaft]" value="Y">
<input name="**model_name**[**id2**][gebuehr]" value="200">
(for an UPDATE page you shouldn't really be allowed to change the id)
That way you can just iterate through the models as:
foreach($_POST['**model_name**'] as $id=>$model){}
and perform the UPDATE on each iteration as before.
UPDATE
I'd also be wary of your code as it is hugely vulnerable to SQL injection.. you should really check the value of each $key against the known columns before spanking straight it into a statement. Otherwise the user can submit their own $key and open up your database.
UPDATE 2
Either pull the columns from the database, or hard code them into whatever PHP model class you are using as an array (saves a trip, but needs doing if you change the schema).
I'd probably assign the values to a keyed array in the model class from the $_POST array before running the SQL, as you may need them later.
N.B.
A lot of these issues have already been solved in the various frameworks out there; no idea what your project is (could be writing a framework) but for anyone stumbling across this frameworks can save a lot of work and security vulnerabilities!

PHP Session Array Duplicating

I'm trying to set a session array with some pre-defined values, which the user can then add to using a simple html form. My problem is that on the page where the array is set, any refresh or revisit of the page just duplicates the pre-defined values within the array. Not only that, but it also overwrites the value coming from the form each time at the end.
So in this basic example, I have a list of animals and a user can add another animal to the list. But this outputs the pre-defined animals again each time i.e. if I submit the form twice (e.g. adding chicken and then dog) I get the output:
Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => pig[5] => cow[6] => sheep[7] => dog)
What I want is:
Array ( [0] => pig[1] => cow[2] => sheep[3] => chicken[4] => dog[5])
What am I doing wrong?
index.php
<?php
session_start();
//pre-defined list of animals
$_SESSION['animals'][] = 'pig';
$_SESSION['animals'][] = 'cow';
$_SESSION['animals'][] = 'sheep';
?>
<!--form to add another animal-->
<form action="go.php" method="POST">
<p><input type="text" name="entry1"></p>
<p><input type="submit" name="submit"></p>
</form>
go.php
<?php
session_start();
//add form entry1 to the session array
$_SESSION['animals'][] = $_POST['entry1'];
//print session array
print_r($_SESSION['animals']);
?>
Only initialize the session variable if it's not already set:
if (!isset($_SESSION['animals'])) {
$_SESSION['animals'] = array('pig', 'cow', 'sheep');
}
Check
in_array('YOUR_VALUE',$_SESSION['animals'])
before re inserting it to avoid duplication.
Reference: in_array
I would suggest to not insert data in the session directly, but adding hidden input values like:
<input type=hidden name=extraValue[] value="pig">
<input type=hidden name=extraValue[] value="cow">
etc
In your PHP page, unset the previous session since you want a 'fresh' dataset based on the input, not on the old values.
unset($_SESSION['animals']);
You can access your extra values in $_POST['extraValue']. You then could merge both arrays like
$postValues = array_merge($_POST['extraValue'], $_POST['entry1']);
I havent tested this code yet, but I would use this 'way', rather than setting SESSION values before input.

html and javascript same name for multiple inputs - how to?

I have never done anything like this, and I would like to know how to do it. I need to put 4 inputs into a sub array if it is field out
I know that when i $_POST the form to the server it sends the names of the inputs but how do I get the input to be allowed to have the same name
for example
the sub array i need it to be in is offers
here is what i dont know. How do i get the following inputs
<input name="offers[]['minspend']" value="15.00"/>
<input name="offers[]['minspend']" value="5.00"/>
<input name="offers[]['minspend']" value="19.00"/>
<input name="offers[]['minspend']" value="8.00"/>
<input name="offers[]['minspend']" value="30.00"/>
<input name="offers[]['minspend']" value="7.00"/>
<input name="offers[]['minspend']" value="100.00"/>
<input name="offers[]['minspend']" value="10.00"/>
is this correct or wrong?
thanks
It depends a bit on the back end technology that processes your request (java, php, whatnot), but from an html standpoint multiple elements with the same name will just send their value with the same parameter name. You don't need any special [] syntax.
GET /mypage.html?offer=15.00&offer=5.0&offer=19.0 (etc, could be post too)
Most languages that provide built in support for html requests represent this request as a map, with a key named "offer" and a value that is an array or list containing the values submitted.
For example http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()
This form
<input name="offers['minspend'][]" value="15.00"/>
<input name="offers['minspend'][]" value="5.00"/>
<input name="offers['minspend'][]" value="19.00"/>
<input name="offers['minspend'][]" value="8.00"/>
<input name="offers['minspend'][]" value="30.00"/>
<input name="offers['minspend'][]" value="7.00"/>
<input name="offers['minspend'][]" value="100.00"/>
<input name="offers['minspend'][]" value="10.00"/>
on doing var_dump($_POST) [assuming form method=post] give:
array(1) {
["offers"] = > array(1) {
["\'minspend\'"] = > array(8) {
[0] = > string(5)"15.00"
[1] = > string(4)"5.00"
[2] = > string(5)"19.00"
[3] = > string(4)"8.00"
[4] = > string(5)"30.00"
[5] = > string(4)"7.00"
[6] = > string(6)"100.00"
[7] = > string(5)"10.00"
}
}
}
So, that is how you do it.
you can remove 's around minspend. they aren't needed.
You were almost there. offers[]['minspend'] means that you get:
array(){
array(){
'minspend' => "15.00"
}
array(){
'minspend' => "5.00"
}
.. and so on
}
So what is happening is, when you do something like arr[] = 1, 1 is inserted into array arr.
Well first let me tell you what i understood from the question. You want multiple input fields to have same name and then you want to select them all to perform some action. If this is the case i'd like to present a different approach - why don't you assign same class (cssclass) to all the controls you want to have same name. That way you'll be able to select them all together using document.getElementsByClassName("yourclassName"). which will return you an array of all the elements having class attribute as yourclassName.
Or if you wanna stick to name then you can use document.getElementsByName("elementName"); which returns you an array of elements having name as elementName.
Hope its helpful.

Is there some list of input's IDs or names of Form after the script was sent?

Let's imagine I got this:
index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php
<form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>
Script.php:
Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.
Is there a way to do this?
i may be missing something in your question, but the $_POST variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:
print_r($_POST);
// contains:
array
(
[1] => 1
[24] => 2233
[55] => 231321
)
// example access:
foreach($_POST as $name => $value) {
print "Name: {$name} Value: {$value} <br />";
}
Use an array_keys on the $_POST variable in script.php to pull out the names you created and use those to get the values.
$keys = array_keys( $_POST );
foreach( $keys as $key ) {
echo "Name=" . $key . " Value=" . $_POST[$key];
}
It sounds like you're using a class or framework to generate your forms, you need to read the documentation for the framework to see if/where it's collecting this data.

Categories