how to loop through a set of GET values in php - 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.

Related

PHP extract each record in variable for insert

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

php cant insert array data into database

the sql :
$sql = $db->prepare('SELECT * FROM product_detail WHERE size = $order_size AND product_id = $order_detail_product_id');
the code:
$order_detail_product_id = $_POST['order']['product_id'];
$order_size = $_POST['order']['size'];
html:
<?php foreach ($it as $e) { >?
<input type="text" name="order[product_id][]" value="<?php echo $e[0]; ?>">
<input type="text" name="order[size][]" value="<?php echo $e[3]; ?>">
<?php } ?>
why that's can't work. the error is array to string conversion
You can't use variables like that inside single quotes in your prepare statement (you'd need double quotes for that to make sense, but it'd still be quite bad and still doesn't make sense cause you're using an array as a string), and also putting the value inside the string you prepare beats the purpose of preparing, you should do:
foreach ($order_size as $key => $size):
$stmt = $db->prepare('SELECT * FROM product_detail WHERE size = ? AND product_id = ?');
$stmt->bindParam(1, $size);
$stmt->bindParam(2, $order_detail_product_id[$key]);
...
endforeach;
Or a different query, depending on what you want, which is not easy to guess with what you posted.
Assuming you're using pdo and not mysqli (which would suck).

How to Insert DropDown Selection into MySQL database?

I am trying to post the value chosen for a dropdown menu into my database table. But for some reason its not inputting the value into the database. I am trying to post cat_id into my database. So i use the code below to geenrate my dropdown list from values i alrady have in the database. Then below i have the function that inserts the info into the database. But for some reason its not working. I am suppose to put what is in select name="" right?
<select name="cat[<?=$row['pk_id']?>]">
<?php $cat = dbConnect("SELECT * FROM category");
if(empty($row['cat_id'])){
?>
<option value="">Select Category</option>
<?php
}
?>
<?php while($cat_r = mysql_fetch_array($cat)){
if($row['cat_id'] == $cat_r['cat_id']){
?>
<option value="<?=$cat_r[cat_id]?>" selected="selected"><?=stripslashes($cat_r[cat_name])?></option>
<?php
continue;
}
?>
<option value="<?=$cat_r[cat_id]?>"><?=stripslashes($cat_r[cat_name])?></option>
<?php } ?>
</select>
Here is my insert to MySQL
dbConnect("INSERT INTO post_info(add_to_random, show_home, source, display_vote_page, cat_id) values(1,1,1,0,cat[.$row['pk_id'].])");
Did i put something wrong here for the value for cat_id? I put cat[.$row['pk_id'].]) which is the select name="" for that dropdown list.
Code ported from comment:
if($_POST and $_POST['action'] == 'submit'){
foreach($_POST as $k=>$v){
$$k = $v;
}
foreach($cat as $k=>$v){
if($v =='') continue;
dbConnect("UPDATE twit_info set cat_id=" . $v . " where pk_id =". $k );
}
if(count($pkid)>0){
$pid = implode(',',$pkid);
dbConnect("UPDATE twit_info set add_to_vote = 1, display_vote_page = 1 where pk_id in(". $pid .")");
}
}
So in your foreach loop, you are extracting all post keys into global variables via the variable variable $$k (I'll get to this in a second). In your dbConnect() call, the quoting is incorrect. You should concatenate in $cat.
dbConnect("
INSERT INTO post_info
(add_to_random, show_home, source, display_vote_page, cat_id)
values(1,1,1,0, '" . mysql_real_escape_string($cat[$row['pk_id']]) . "')" );
I have added a call to mysql_real_escape_string(). This is necessary at a minimum, to protect all your queries from SQL injection. Your other UPDATE statements are also vulnerable at this point and you MUST perform some escaping on them as well.
Regarding the extraction of $_POST into global variables - I highly recommend against this. You are in effect imitating the behavior of register_globals which is considered very dangerous. The danger comes in that it is possible for anyone to post any key to your form, in addition to the ones you actually expect to receive, potentially initializing another variable in your script to a value sent via $_POST when your script doesn't expect it.
Although I really just recommend operating on $_POST directly, rather than extracting to global variables, if you must extract them to globals, I advise you to use a whitelist of acceptable $_POST keys:
// Make an array of allowed keys
$good_keys = ('action', 'cat', 'otherformkey');
foreach($cat as $k=>$v){
// Only extract if it is one of the allowed keys
if($v =='' || !in_array($k, $good_keys) continue;
// Cast to an integer
$v = intval($v);
$k = intval($k);
// Non-integer strings will cast to zero, so don't do the db action.
if ($v > 0 && $k > 0) {
dbConnect("UPDATE twit_info set cat_id=" . $v . " where pk_id =". $k );
}
// For string values which are quoted in the SQL (unlike the int values above)
// escape them with mysql_real_escape_string()
// $v = mysql_real_escape_string($v)
}

Insert Form Checkboxes PHP separated by comma - Retrieve them

I was looking in stackoverflow, but i do not find exactly what I need. I need to insert checkboxes data sent with php into mysql like this 22111,22332,12123,121132.
I have this code (found here in the site)
<?php
foreach($_POST['idecod'] as $check) {
$sel = $check.',';}
$contenedor = "UPDATE inmdes SET idecod='$sel'";
$insertdb = mysql_query($contenedor) or die(mysql_error());
?>
Of course I have the checkboxes as an array:
<input name="idecod[]" type="checkbox" value="<?php echo $rs[0]; ?>" />
How can i insert multiple checkboxes like 2211223,2211223,1212233,12332122 or if is just one 222111222..???
And how can i retrive them as an array because i need to use something like this
<? php if (in_array('2211223', $idecod)) echo "checked"; ?>
To automatically check the previous checked boxes.!
Thanks in advance
Roberto
UPDATE
I have a list of options. These options act/des with checkboxes. I need to:
1.- Be able to register options checked (SOLVED thanks to #prodigitalso)
2.- Be able to automatically check the checkboxes previously checked.
So, I have the codes like this 221122,221133,225566,445522 in the table (mysql). I need the script to check what codes where previously checked (those that are in the table) and check them. For example:
I see the 5 options 221122,221133,225566,445522 and 663322. I check only 4 (221122,221133,225566,445522) and this is UPDATED in mysql database.
I come again to the options page. But previously i checked 221122,221133,225566,445522. So the script check EACH checkbox. So automatically check options 221122,221133,225566,445522 BUT it doesnt check 663322.
RS[0] is the code, for example 221122.
You can use implode and explode function to do this
$string = implode(",", $array);
$array = explode(",", $string);
You should use explode and implode.
if(isset($_POST['idecod']) && !empty($_POST['idecod'])) {
$sel = implode(',', $_POST['idecod']);
$contenedor = sprintf("UPDATE inmdes SET idecod='%s'", mysql_real_escape_string($sel));
$insertdb = mysql_query($contenedor) or die(mysql_error());
}
then when you pull them out just use:
$idecodArr = explode(',', $row['idecod']);

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];

Categories