PHP extract each record in variable for insert - php

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')";

Related

insert 100+ variables into query string

I have an online survey format with approx 200 input / select fields which I now want to write into my database. Now, since I dont want to go through the tedious process of writing out every single variable one-by-one in the query string, I was hoping that there would be an easier way, eg. using an array?
Here is a solution that I use. It requires that the database field names are the same as the <input> names:
$querystring1 = ""; $querystring2 = "";
foreach($_POST as $key => $var) {
$querystring2 .= "'".$var."',"; $querystring1 .= $key.",";
}
$insertquerystring = "(".$querystring1.") VALUES (".$querystring2.")";
mysql_query("INSERT INTO `mytablename` $insertquerystring") or die(mysql_error());

Multiple Inputs Insert

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.

Multiple Rows Update with same form names in PHP

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?

Using $_POST in While PHP Question

I'm trying get some information via $_POST in PHP, basically at the moment i'm using this:
$item_name1 = $_POST['item_name1'];
$item_name2 = $_POST['item_name2'];
$item_name3 = $_POST['item_name3'];
$item_name4 = $_POST['item_name4'];
I want to insert each of the item names in a table field with mysql so i'm trying to experiment with the while php loop so i dont have lots of $item_name variables:
$number_of_items = $_POST['num_cart_items'];
$i=1;
while($i<=$number_of_items)
{
$test = $_POST['item_name'. $i''];
$i++;
}
The above code fails, its pretty tricky to explain but the code should find all the item_name $_POST and make it as a variable for mysql insertion.
The $_POST['num_cart_items'] is the total number of items.
The code is for a PayPal IPN listener for a shopping cart that is underway.
Help appreciated.
EDIT:
I have this further up the document which i just realised:
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
How can i insert $_POST['item_name1'], $_POST['item_name2'] as a variable for mysql insertion?
Your loop is effectively overriding the $test variable on each iteration:
$test = $_POST['item_name'. $i''];
If you want to put them in an array, change to $test[]. Also it contains the parse error as mentioned by brian_d.
It sounds a little scary to have a variable num_cart_items that is sent with the form. Are you setting it with JavaScript? The user can manipulate it. You should not rely on it. I belive what you need is to make the form feilds as:
<input type="text" name="item_name[]" />
Note the square brackets at the end of the name. This will create an array in the $_POST array: $_POST['item_name'] will contain the names of all the items.
Then, how is your DB structured? I guess you want to insert them in one query as:
INSERT INTO ORDERS VALUES (item_name_1, ...), (item_name_2, ...)
If so you can make a string out of the array:
$query = 'INSERT INTO ORDERS VALUES ';
foreach($_POST['item_name'] as $item_name){
$query .= '('.stripslashes($item_name). /*put other column values*/ '),';
}
$query = rtrim($query, ',');
Note that the use of addslashes is not enough to protect you from SQL injection.
$test = $_POST['item_name'. $i'']; is a syntax error.
remove the end '' so it becomes:
$test = $_POST['item_name'. $i];

how to loop through a set of GET values in php

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.

Categories