Looping through $_POST variables - php

Sorry i could not find a proper title to this question.
I have generated the following using a for loop and I have concatenated the names of the submits buttons using the pattern below:
submit_edit_category_1
submit_edit_category_2
submit_edit_category_3
echo "<input type='submit' value = 'Edit' name='submit_edit_category_" .
$obj_categories_admin->categories[$i]['category_id'] . "'/>";
I want to loop through these values so that I can the button action whichis edit_category and the category id which is 1,2 or 3. I want to so something like:
if(isset($_POST) == 'edit_category'))
{
//code here
}
Someone suggested me to do it this way:
name="submit[which_action][which_category]"
a1 = $_POST['submit'];
$which_action = reset(array_keys($a1));
$which_category = reset(array_keys($a1[$which_action]));
This does not seem to work..Can anyone give me a different way to do it?
Thanks!

UPD: Please, use Mike's advice. It's much better to have more structured data in POST.
foreach($_POST as $key => $val) {
if(strpos($key, 'submit_edit_category_') === 0 ) {
print $key.' => '.$val.'\r\n';
print substr($key, 21 /* or 22... or 23... try yourself */ );
}
}

here what I'd do:
for the actual form, I'd use array keys to communicate action and relevant id info.
$cat_id = $obj_categories_admin->categories[$i]['category_id'];
echo "<input type='submit' value = 'Edit' name='submit[edit_category][" . $cat_id . "]'/>";
then when posted, I can do:
<?php
list($action, $action_params) = each($_POST['submit']);
list($cat_id, $button_label) = each($action_params);
print_r($_POST['submit']); // prints array('edit_category' => array('1' => 'Edit'))
echo($action); //prints "edit_category"
print_r($action_params); //prints array('1' => 'Edit')
echo($cat_id); //prints "1"
echo($button_label); //prints "Edit"
edit: for more info on each(), go here: http://us2.php.net/each . I've personally always felt that 's lack of differentation between the button label and the it's value to be frustrating. Using an array key to stuff info into the button has always been my favorite hack.

You can try this:
foreach ($_POST AS $key=>$value) {
if (strpos($key, 'submit_edit_category_') !== false) {
$catID = (int)str_replace('submit_edit_category_', '', $key);
echo 'Category ID: ' . $catID . '<br />';
}
}

I'd change the way you build the name to this:
submit__edit_category__1
Then, try this:
function filter_by_submit($var)
{
return stripos($var, "submit") !== false ? true : false;
}
$submits = array_filter(array_keys($_POST), "filter_by_submit");
foreach ($submits as $sub)
{
if ($_POST[$sub] == "Edit")
{
list($submit, $action, $id) = explode("__", $sub);
break;
}
}
$submit will hold the string "submit". $action will hold "edit_category" and $id will hold the id of the pressed button. The pressed button is determined by matching its value to the tag's value (i.e., when submit__edit_category__1 is pressed, the value "Edit" is POSTed).

Related

PHP => $_SESSION Array only keeps last variable

I'm building an interface for an online shop, where every item is a FORM and the BUY button is a submit,it submits the name and price of the clicked form and that data is displayed on a CONFIRM ORDER page. On that confirm order page I've created an array as follows
if (!isset($input_order_arr)) {
$input_order_arr = array();
}
After that I fetch the posted variables and push them into the array
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
$item_title = test_input($_POST['item-title']);
$item_price = test_input($_POST['item-price']);
array_push($input_order_arr,$item_title,$item_price);
}
}
$_SESSION['chosen_item'] = $input_order_arr;
*NOTE : test_input is a function that does striplashes , htmlspecialchars and htmltrim, for security purposes. (someone might edit the value of the item via the Chrome developer console? not sure if that holds any threat though)
And after that the value is displayed in a table like so
<?php if (isset($_SESSION['chosen_item'])) {
foreach ($_SESSION['chosen_item'] as $value) {
echo "<td>" . $value . "</td>";
}
} ?>
And here comes the problem.
If you order an item its price and name are displayed, but if u go back and you order another item, the previous item and its price are lost, as if its not adding new lines to the array,but replacing the old ones, or the session only saves data from one action, which wouldn't make any sense, since thats what $_SESSION is about, the code is presented with session_start(); in every page that is using the $_SESSION variable.
Main Question - Why could it be that the $_SESSION Array is losing its older inputs?
You could push directly into the session like this
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
array_push($_SESSION['chosen_item'],
test_input($_POST['item-title']),
test_input($_POST['item-price'])
);
}
}
//$_SESSION['chosen_item'] = $input_order_arr;
Or as your test_input() is likely doing nothing useful
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
array_push($_SESSION['chosen_item'],
$_POST['item-title'],
$_POST['item-price']
);
}
}
You might find this data easier to use later by doing
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
array_push($_SESSION['chosen_item'],
array('title' => $_POST['item-title'],
'price' => $_POST['item-price']
)
);
}
}
you need $_SESSION['chosen_item'][]=$input_order_arr; your overwriting the same index instead of creating new one
$_SESSION['chosen_item'][]=$input_order_arr;
Note : And also it should be moved inside the if statement .to avoid empty array storing in session
When you go back, you basically are setting the chosen_item array element to empty, since $input_order_arr would not contain anything when you haven't submitted a form.
You should append to the session array only if there is a nonempty $input_order_arr array:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['item-title']) && !empty($_POST['item-price'])) {
$item_title = test_input($_POST['item-title']);
$item_price = test_input($_POST['item-price']);
array_push($input_order_arr,$item_title,$item_price);
$_SESSION['chosen_item'][] = $input_order_arr;
}
}

get a value from key value pair list in php

I want to display a specific value from key value list..
here is my code:
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
ouput
ORDERID = ORDS3700373
TXNAMOUNT = 200.00
CURRENCY = INR
TXNID = 32221284
BANKTXNID = 475815
STATUS = TXN_SUCCESS
RESPCODE = 01
RESPMSG = Txn Successful.
TXNDATE = 2017-01-10 18:13:25.0
GATEWAYNAME = WALLET
BANKNAME =
PAYMENTMODE = PPI
CHECKSUMHASH =
here I want to display only ORDERID and TXNID.. How do I get that value?
You can easily access post values by it's field name instead of looping through all post elements. Simply access that elements directly as below:
if(isset($_POST['ORDERID'])) {
echo 'ORDERID = '.$_POST['ORDERID'];
}
if(isset($_POST['TXNID'])) {
echo 'TXNID= '.$_POST['TXNID'];
}
Moving comments to an answer.
You do not need to loop post it is just a global array. You can access the values at any of the keys like any associative array because that is what it is. Likewise these value can be used like any other
if(isset($_POST['ORDERID'])){
$orderid = $_POST['ORDERID'];
}
if(isset($_POST['TXNID'])){
$txnid = $_POST['TXNID'];
}
// Should use htmlspecialchars() or htmlentities() here
// but didn't want to confuse OP. It is for security.
echo "ORDERID is: " . $orderid . " and TXNID is: " . $txnid;
A note for security never trust user input and sanitize all $_POST variables before echoing or persisting. There are far better article out on the internet than I can summarize here.
You can use if condition in the loop like this
if (isset($_POST) && count($_POST)>0 )
{
foreach($_POST as $paramName => $paramValue) {
if($paramName == 'ORDERID' || $paramName == 'TXNID')
echo "<br/>" . $paramName . " = " . $paramValue;
}
}
add an if like
if($paramName == "ORDERID" || $paramName == "TXNID") {
after foreach, remeber to close it after echo statement line
Don't overcomplicate a trivial task with a loop.
Just drop the loop and echo the two values directly:
// Assuming the two values are expected to come in pair:
if(isset($_POST['ORDERID']) && isset($_POST['TXNID'])) {
echo "<br/>ORDERID = " . $_POST['ORDERID'];
echo "<br/>TXNID = " . $_POST['TXNID'];
}
If you insist on having a loop, then you can go through the property names which you need
foreach(array('ORDERID', 'TXNID') as $paramName) {
if(isset($_POST[$paramName])) {
echo "<br/>" . $paramName . " = " . $_POST[$paramName];
}
}

php check empty or null in many variables

Hello I have a simple script
This is my script, and try this script
<?php
$user_id = $_REQUEST['user_id'];
$pid = $_REQUEST['pid'];
$nopr = $_REQUEST['nopr'];
$tglpr = $_REQUEST['tglpr'];
$uraianpr = $_REQUEST['uraianpr'];
$jenispr = $_REQUEST['jenispr'];
$nilaipr = $_REQUEST['nilaipr'];
$costproject = $_REQUEST['costproject'];
$remarkpr = $_REQUEST['remarkpr'];
$tmpattachid = $_REQUEST['tmpattachid'];
if ($user_id==NULL)
{
$error "User Id Not Complete";
}
else if ($pid==NULL)
{
$error= "PID Not Complete";
}
echo $error;
?>
I want if $user_id or other variables is empty/null
i confused when other variable have empty/null data
i must typing code many if statement :(
example : 5 variables ($pid,$nopr,$tglpr,$jenispr,$costproject) is empty/null
this show error like this
PID Not Complete
NoPR Not Complete
Tgl Pr Not Complete
Jenis Pr Not Complete
Cost Project Not Complete
Help Me, Thank's.
I won't give you the full answer, as stated in comments, this is a basic basic concept you need to learn, but I will show you the template.
You want to use a FOREACH loop to check each value in the array. See http://php.net/manual/en/control-structures.foreach.php
And Set it out like this:
foreach($_REQUEST as $key=>$row){
if (is_null($row) || empty($row)){
$errorText .= "You have no data in your ".$key."<br>";
}
}
unset($key,$row);
Then you can output the $errorText value telling people which rows should be fixed. Easy.
Loop through the $_REQUEST and find the empty or null key.
CODE :
foreach ($_REQUEST as $key => $value) {
if(trim($value) ==='' || is_null($value))
{
echo $key . " is not complete" . "<br/>";
}
}

PHP improve my show message function

I'd like some help please, if its possible.
I have created two functions in order to display some messages when is set a $_GET after a redirect.Here's the code:
function display(){
if(isset($_GET['cnf_upd']) && $_GET['cnf_upd'] == '1'){
$value = "The update was successful!";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_upd']) && $_GET['err_upd'] == '1'){
$value = "The Update failed.";
$type = "error";
construct_the_div($value, $type);
}
if(isset($_GET['cnf_del']) && $_GET['cnf_del'] == '1'){
$value = "Deleted completely.";
$type = "confirm";
construct_the_div($value, $type);
}
if(isset($_GET['err_del']) && $_GET['err_del'] == '1'){
$value = "Unable to delete.";
$type = "error";
construct_the_div($value, $type);
}
}
function construct_the_div($value, $type){
// creating a div to display the message results
$div = "<div class=\"{$type}Msg\">\n";
$div .= "<p>{$value}</p>\n";
$div .= "</div><!-- end of {$type}Msg -->\n";
echo $div;
}
What I'd like to make is to try to improve the display function, as it gets longer and longer, so that there whould be only one (or two at most) if statement(s) if possible. So the value of the GET will be dynamicly inside the if condition and also if it has the preffix 'cnf_' it wil be a 'confirmMsg' and if it has the preffix 'err_' it wil be a 'errorMsg'.
Is it possible to make something like this???
function display() {
$messages = array(
'cnf_upd' => 'The update was successful!',
'cnf_err' => 'The Update failed.!',
// ...
// add all error and confirm there
// ...
);
foreach($_GET as $key => $value) {
if(strpos($key, 'cnf_')===0) {
$type = 'confirm';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
if(strpos($key, 'err_')===0) {
$type = 'error';
$value = isset($messages[$key])
? $messages[$key]
: $key;
construct_the_div($value, $type);
}
}
}
The approach is not correct, it seems that only one message should occur at once (there cannot be "deleted completely" and "unable to delete" at once).
Try construct the parameters this way: ?msg=upd&msgType=cnf
function display(){
if (isset($_GET['msg']) && isset($_GET['msgType']))
{
$messages = array('cnf_upd'=>'The update was successful!',
'err_upd'=>'The update failed!',
'cnf_del'=>'The deletion was successful!',
'cnf_upd'=>'The deletion failed!',
);
if (isset($messages[$_GET['msgType'].'_'.$_GET['msg']))
construct_the_div($messages[$_GET['msgType'].'_'.$_GET['msg']], htmlspecialchars($_GET['msgType']));
}
there is still much to improve, but for start this is cleaner and safer.
I'm going to propose a different solution. Instead of setting different parameters in $_GET based on the message to be sent, set one parameter and parse its value.
// Start by setting integer constants:
define(CNF_UPD, 1);
define(ERR_UPD, 2);
define(CNF_DEL, 3);
define(ERR_DEL, 4);
Then when you set the value un $_GET, use the constant:
// Build the URL with a deletion error...
header("Location: http://example.com/script.php?msg=" . ERR_DEL);
Finally, use a switch to parse them
if (isset($_GET['msg'])) {
switch ($_GET['msg']) {
case CNF_UPD:
// Updated...
break;
case ERR_UPD:
// failed...
break;
// etc...
default:
// invalid code.
}
}
If you use a pattern of confirm/error/confirm/error for your integer constants, you can determine which it is by taking $_GET['msg'] % 2. Odd numbers are confirmations, evens are errors. There are of course many other ways you could lay this out, I just happen to have typed them in the alternating order you used. You could also do positive integers for confirmations and negatives for errors, for example.
$type = $_GET['msg'] % 2 == 1 ? $confirm : $error;
This is easily expanded to use multiple messages as well. Since they are integer values, you can safely construct a comma-separated list and explode() them when received.
$messages = implode(array(ERR_DEL,CNF_UPD));
header("Location: http://example.com/script.php?msg=$messages");
Unless you can somehow generate $value and $type based on the $_GET parameter (which I can't see how you would do), you could do something like:
$messages = array();
$messages[] = array('id' => 'cnf_upd', 'value' => 'The update was successful!', 'type' => 'Confirm');
$messages[] = array('id' => 'err_upd', 'value' => 'The Update failed.', 'type' => 'error');
...
foreach ($messages as $message) {
if(isset($_GET[$message['id']]) && $_GET[$message['id']] == '1'){
construct_the_div($message['value'], $message['type']);
}
}

PHP check values

We have 2 variables, $id and $title.
And a form field for a new $title variable:
foreach ($ids as $id) {
$id_title = $title;
?>
<input name="new_<?php echo $id; ?>_title" value="<?php echo $id_title; ?>" />
<?php } ?>
How to check, is $id_title has been changed in the form, and do something if it is.
Like:
if ($id_title != $new_id_title) {
make db query
}
There can be more than one input field on the page, different for each $id, we should check all of them.
Thanks.
Something like this?
foreach ($ids as $id) {
if (isSet($_POST["new_{$id}_title"]) && $_POST["new_{$id}_title"] != $old_titles[$id]) {
// Do foo
}
}
You mean
foreach ($ids as $id) {
$id_title = $title;
if ($id_title != $_POST['new_'.$id.'_title']) {
make db query
}
}
?
Is the problem that you don't know how to get the new_$id_title field?
Btw. I don't see a point to assign $title to $id_title. It is the same for all anyway.

Categories