I wasn't sure what to title this question. Here's my goal:
On page one, I have a form that is generated from the database. It loops through assigning a counting variable to the id of the fields (ie: header_1, header_2, header_3...)
Now, the amount of fields may vary as I need the ability to add extra information (ie: header_4, header_5).
When I submit my form, how can I create a variable for each field?
$header1 = $_POST['header_1']
Essentially, I am looking for an array-based (or variable variable-based) way of simplifying something like this:
$sql="UPDATE about SET about_header = '$head1', about_content = '$post1' WHERE about_id = '$id1'";
$result = mysql_query($sql);
$sql="UPDATE about SET about_header = '$head2', about_content = '$post2' WHERE about_id = '$id2'";
$result = mysql_query($sql);
$sql="UPDATE about SET about_header = '$head3', about_content = '$post3' WHERE about_id = '$id3'";
$result = mysql_query($sql);
I imagine a query like this would work but I'm not sure how to handle the array of information that I would need help building as well.
$y=1;
$sql="UPDATE about SET about_header = '$head$y', about_content = '$post$y' WHERE about_id = '$id$y'";
I hope I explained this well enough. Any help would be great. Thanks!
have you ever tried something like:
<input name="header[]" />
<input name="header[]" />
<input name="header[]" />
This will create a multi-dimensional array on the PHP side which you can easily cycle through.
echo $_POST['header'][0];
echo $_POST['header'][1];
echo $_POST['header'][2];
It would also be faster to use prepared statements for this, although you would have to switch to using something like PDO for your database interactions. Here's an example of looping thorugh using the code you showed above.
$fieldCount = count($_POST['header']);
for ($i = 0; $i < $fieldCount; $i++) {
$sql = 'UPDATE about SET about_header = \''.$_POST['header'][$i].'\', about_content = \''.$_POST['post'][$i].'\' WHERE about_id = \''.$_POST['id'][$i].'\'';
mysql_query($sql);
}
<input type="text" name="head[]" />
<input type="text" name="head[]" />
<input type="text" name="head[]" />
<?php
foreach ($_POST['head'] as $head) {
// ....
}
?>
Naming your inputs like this (note the array-ish notation) will yield
$_POST == array( 'head' => array(
0 => FIRST TEXT DATA,
1 => SECOND TEXT DATA,
2 => THIRD TEXT DATA
))
Related
I am building a page that writes out a varying number of categories and then, under each category, writes out the units associated with that category. Each category section is a single form with fields that are repeated and named according to what row they belong to. The layout is like this:
Category 1
Unit 1 Update Fields
Unit 2 Update Fields
Unit 3 Update Fields
Submit Button for Category 1
etc.
Each field is named the same thing with the unit number added on the end:
Features1, Features2, Features3, etc.
The total number of rows in a given category is held in the variable $id# where # is the category's ID (ex: $id1, $id2, $id3, etc).
I've got most of this sorted out. However, I want to loop through and perform a SQL query if the form has been changed, and that's where I'm having trouble. At this point, I'm at a loss. Here is a simplified version of my code:
if (isset($_POST['submit'])) {
$form = $_POST['form']; //save which category we're on in a variable.
for ($i = 1; $i <= ${id.$form}; $i++) { //I think the problem is here
$Feature = $_POST['Feature'.$i];
$update = "UPDATE Units
SET Feature ='$Feature'
WHERE ID='$i'";
if (($Feature!=${initialFeature.$i})) {
$updateQuery = mysqli_query($dbc, $update);
}
}
}
How can I make this work? Is there a better way to do this?
The way I would do it is using an array in field names.
<input type="text" name="id[]" value="$foo">
Then on the action page for the form
$id = $_POST['id'];
for($i=0;$i<sizeof($id),$i++){
...//do something here using $id[$i] to select elements in the array
}
I think that is what you're trying to do.
try this
for($i=0; $i<3; $i++)
echo '<input type="text" name="feature[]" value=""/>';
echo '<input type="submit" name="go" value="submit">';
if (isset($_POST['go'])) {
$feature = $_POST['feature'];
if(is_array($feature)){
for ($i = 1; $i <= count($feature); $i++) {
$update = "UPDATE Units
SET Feature ='$feature[$i]'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}else{
$update = "UPDATE Units
SET Feature ='$feature'
WHERE ID='$i'";
$updateQuery = mysqli_query($dbc, $update);
}
}
hope this code can solve your problem
Here is my PHP variable:
$container = $_POST['containerNumber'];
Inside $_POST['containerNumber'], there are multiple container numbers that are retrieved when a user checks a checkbox from a form. That code is not necessary to display. Just know that $_POST['containerNumber'] can have multiple container numbers assigned to it.
What I need to do is extract each container number from the POST so that I can run a mysql INSERT statement per each container number.
In the database table, there are multiple columns, with container_num being the column I'm trying to update (for now).
How can I turn $container into an array and retrieve each container number that has been assigned to the variable?
I know I need to utilize a FOREACH loop. With that said, there will more than likely be multiple INSERT statements that will automatically be created with the loop.
$SQL = "INSERT INTO myTable (container_num) VALUES ('$container')";
// times however many containers the variable $container had stored in it
Please help.
EDIT **
Once the user checks however many checkboxes, I can display each container like this:
<INPUT name="containerNumber" id="containerNumber" class="containerNumber" />
When I do this, it can be displayed to the screen like this:
CONT_ID001, CONT_ID002, CONT_ID003...
I hope this helps.
There are multiple ways of doing this.
1) Give the POST parameters you're sending a name that ends with [], PHP automatically assigns them to an array when parsing the POST data. If you're sending the data from an HTML form, this is an example of how to do it:
<form action="" method="POST">
<label>
First container number:
<input type="text" name="containerNumber[]" />
</label>
<label>
Second container number:
<input type="text" name="containerNumber[]" />
</label>
<input type="submit" />
In PHP you can just do
foreach($_POST["containerNumber"] as $container) {
...
}
(Note that this is a feature of PHP and not portable to other server-side langages. This is NOT part of the HTTP specification.)
2) Separate values using some separator, in PHP use explode() to split it.
3) Send the form as JSON or encode that one field as JSON (if sent from HTML, I suggest using jQUery to do either option, as it's the easiest way) and use json_decode() in PHP to extract the contents.
4) Sevaral other options that may be suitable, depending on what exactly you're doing.
If I get you, you have a $_POST variable with multiple values.
If the content of $_POST['containerNumber'] is CONT_ID001, CONT_ID002, CONT_ID003
You can do this:
$result = preg_split("/, /", $_POST['containerNumber']);
//the result dump will be:
//$result[0] = "CONT_ID001";
//$result[1] = "CONT_ID002";
//$result[2] = "CONT_ID003";
The insert code should looks like to (assuming that you have one column for each number):
$SQL = "INSERT INTO myTable ";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$columns .= "container_$id";
$values .= "'$out'";
if (count($result) < $id+1){
$columns .= ", ";
$values .= ", ";
}
}
$SQL .= "($columns) VALUES ($values)";
If you only have container_num column it should looks like:
$SQL = "INSERT INTO myTable (container_num) VALUES ('";
$columns = "";
$values = "";
foreach (result as $id=>$out){
$values .= $out;
if (count($result) < $id+1){
$values .= ", ";
}
}
$SQL .= "$values')";
I have an application that looks like this:
As you can see, each row contains either a group heading (the rows where there is just an input), or a ingredient form (where there is a small input, then a select, then another larger input).
I use Javascript to add the new spans. I use the following PHP to group each ingredient span into an array, determine the order (because each span can be moved to a different order), and insert into my database.
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
$ingredientQTY = $this->input->post('ingredientQTY');
$measurements = $this->input->post('measurements');
$ingredientNAME = $this->input->post('ingredientNAME');
$ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'ingredientamount' => $ingredientQTY[$i],
'ingredientType' => $measurements[$i],
'ingredientname' => $ingredientNAME[$i],
'recipe_id' => $recipe_id,
'order' => $i + 1,
'user_id' => $user_id
);
$sql = "INSERT `ingredients` (`ingredientamount`,`ingredientType`,`ingredientname`, `recipe_id`, `order`, `user_id`) VALUES ";
$coma = '';
foreach ($rows as $oneRow) {
$sql .= $coma."('".implode("','",$oneRow)."')";
$coma = ', ';
}
}
$this->db->query($sql);
break;
}
This works wonders for inserting the ingredient rows. But I'm not sure how to insert group headings (which must be placed in the for loop to keep the order, the $i + 1, going).
I think I've figured out two solutions(though there may be others, and these might not even work):
Have the group heading input field have the same name value as one of the ingredient text fields, and send a hidden value along with it, saying its a group heading?
Send it as different input field with a different name value?
My question is: how can I do this with my current code, and are either of these efficient solutions, or is there an even better solution?
Thanks for all help! If you need more details, just ask!
You could use an empty heading like <input type="hidden" name="groupheading[]" value="product" /> and the open one like <input type="text" name="groupheading[]" value="" />. The first one should be inside the product-span.
This way, you can continue your loop just the way you are doing now. And $_POST['groupheading'][$key] either returns a groupheading or the phrase 'product'. So, in your script it would be:
if($_POST['groupheading'][$key] == "product") {
// insert product
} else {
// insert group heading
}
I think I helped you this morning or yesterday with an answer.. it's still a bit a weird way you are using to get the effect you need. It can be achieved much easier.
I'm getting caught up on PHP again, and have the following update code. This works, but only for the last one inserted? I need to update for all gritem id's. I thought adding the [] to a form field that is not unique allows PHP to parse it as an array, but it still sees it as one field?
My HTML I have:
<input type="hidden" name="gritemid[]" value="<?PHP echo $row2['gritemid']; ?>">
<input type="text" name="grqty[]" id="grqty[]" value="" />
The Following PHP code
if(isset($_POST['storageloc']))
{
//Set the GRQTY to subtract from the Orderqty on each item in the list if selected
// find out how many records there are to update
$size = count($_POST['gritemid']);
// start a loop in order to update each record
$i = 0;
while ($i < $size) {
// define each variable
$gritemid= $_POST['gritemid'][$i];
$grqty= $_POST['grqty'][$i];
if ($grqty > "0") {
// do the update and print out some info just to provide some visual feedback
$query = "UPDATE gr_items SET orderqty = orderqty - $grqty WHERE gritemid = '$gritemid' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
}
++$i;
}
mysql_close();
First of all, you really should do some validation/sanitisation of your post vars before dropping them into a query. As both the vars you are using appear to be integers I would suggest using intval() -
// define each variable
$gritemid = intval($_POST['gritemid'][$i]);
$grqty = intval($_POST['grqty'][$i]);
If you replace your call to mysql_query() with print($query); do you see the multiple queries that you would expect?
I'm making a simple online store like program. What can you suggest that I would do so that I can loop through the inputs I've made in my program.
I'm still using get so that I could see how the data looks like, I'll change it to post later.
This is what the url looks like, when I commit the buying of all the products added in the cart:
http://localhost/pos/php/checkout.php?ids=2;&qoh=12;&qbuys=&ids=6;&qoh=2304;&qbuys=304&ids=4;&qoh=699;&qbuys=99
This is the code that I'm using to commit only one product, it doesn't work when I had something like in the above url:
<?php
$id=$_GET['ids'];
$qtyhnd=$_GET['qoh'];
$qtytbuy=$_GET['qbuys'];
$left=$qtyhnd-$qtytbuy;
if($qtyhnd>=$qtytbuy){
$update=query_database("UPDATE prod_table SET QTYHAND='$left' WHERE PID='$id'", "onstor", $link);
}
?>
Please comment if you need more details,thanks
Either convert the parameters to array parameters (e.g. qoh[]) and then iterate in parallel, or parse the query string manually.
You have semicolons after some values maybe you should pass just the integer this are qoh and qbuys.
Apart of that you should use mysql_real_escape_string() and (int) before integer values to prevent SQL injection e.g.:
$int = (int)$_GET['price'];
$string = $_GET['val'];
mysql_real_escape_string($string);
Also if you want to pass multiple values you have to use array for them:
HTML
<input type="hidden" name="ids[]" value="1">
<input type="hidden" name="ids[]" value="2">
<input type="hidden" name="ids[]" value="3">
PHP
$ids = $_GET['ids'];
foreach($ids as $id) {
$sql = 'UPDATE table SET field=? WHERE id='.(int)$id;
....
}
You can use the $_SERVER['QUERY_STRING'] with foreach loop like this:
foreach($_SERVER['QUERY_STRING'] as $key => $value){
echo "$key - $value <br />";
}
This way you can get the values of GET and use in your database query in similar fashion using foreach loop.
I assume that PID in prod_table is of integer type. Doesn't $id variable contain "2;" instead of 2? Anyway, what kind of error do you get?
Have your url like
http://localhost/pos/php/checkout.php?ids[]=2&qoh[]=12&qbuys[]=&ids[]=6&qoh[]=2304&qbuys[]=304&ids[]=4&qoh[]=699&qbuys[]=99... using a HTML structure like infinity pointed out.
Then:
foreach ($_GET['ids'] as $k => $v) {
$id = (int)$v;
$qtyhnd = (int)$_GET['qoh'][$k];
$qtytbuy = (int)$_GET['qbuys'][$k];
$left = $qtyhnd - $qtytbuy;
if ($qtyhnd >= $qtytbuy) {
$update = query_database(
"UPDATE prod_table SET QTYHAND='$left' WHERE PID='$id'",
"onstor",
$link);
}
}
And if the database type of QTYHAND and PID are int, exclude single quotes (') from your SQL queries.