How to get the right forms value from a button click - php

Overview of what my question is:
I have an array that is populated via XML inputs, and from this I am the using it to populate a web form with form controls. From here I want to be able to select the exact form that is clicked, but to do that I need to give the controls some form of unique identifier, which is an issue...
As the site is of a betting nature and I am currently working with horse racing, each horse is given a unique identifier by default, I have tried to add this identifier to the forms.
e.g:
<?php
//Values from feed examples: 123, 234, 345
$valuesFromFeed = array(123, 234, 345); //These are not in my code, they are values from the XML feed
while ($uniqueIdentifier = $valueFromFeed) {
<form name="horse_<?php echo $uniqueIdentifier; ?>_frm" action="#">
<input type="hidden" name="horse_<?php echo $uniqueIdentifier; ?>" />
<input type="button" value="Place bet" />
</form>
}
?>
But then the problem comes when I try to reference this name of "horse_123", I need to know exactly what the value of that name is, which is impossible as there are millions of horses, tracks and races.
Example of trying to get post:
<?php
if (isset($_POST['horse_' . $uniqueIdetifier])) {
echo "You got the right thing here.";
} else {
echo "Still no joy.";
}
?>
The issue with the code above, is that once the $uniqueIdentifier has been used in the while above, it is removed and is no longer usable in this scope.
So to conclude, my point and question:
How do I get the correct name from the form in a submit for the specific horse that I wish to reference and get information on?
How do I use this information as I need to?
Better Description:
I have been given an XML feed and site as part of a handover, this feed contains many hundreds of races and horses.
When this information is loaded into the page, it is also stored in a database on the server, as well as sending it through some different loops (which are messy, but someone else's code I'm trying to clean up!) which split it down and then make up a dynamic menu containing all the races, horses, odds and information. (All information on a single horse within a race is kept in one form)
Next to the information stated in the prior paragraph, is 2 buttons, one that allows the user to take odds and another that allows users to take starting price.
On either of these button clicks, I need the information attached to said horse, and then populate a betting slip. In the form (mentioned above) the name is "horse_<?php echo $uniqueIdentifier; ?>_frm".
The problem that occurs to me is, yes data is stored on the server when it is loaded, that I cannot seem to get the right form via the unique identifier that is put into the form name
Edits
Added form surrounding my input as this is there, I just missed it in original question
Added the button that transmits data to where I need it
Added a better description of my problem

You can use multiple forms, one for each horse. Each form has a different action, where the URL includes the id of the horse. For example:
<form action="/horses/my_unique_horse_name">
...
</form>
<form action="/horses/another_horse_name">
...
</form>
Or you could have multiple forms all with the same action, with a hidden field for the name of the horse:
<form action="/horses/">
<input type="hidden" value="my_unique_horse_name">
</form>
<form action="/horses/">
<input type="hidden" value="another_horse_name">
</form>
Alternatively, you could have a button for each horse:
<form method="/horses/">
<button type="submit" value="my_unique_horse_name">My Horse</button>
<button type="submit" value="another_horse_name">Another Horse</button>
</form>
Beyond that, I don't entirely understand the problem. What kind of data are you submitting and retrieving?

Related

How to use input submit value and GET (link the submit value to another page) in a single click?

I am trying to input submit value and want to pass the value to another page through GET but for that I have to use two Clicks button.
I want the same in a single click. Help required.
Code:-
<form method="post">
<input name="inwardid" type="text" id="inwardid" />
<?php $inwardid = $_POST['inwardid']; ?>
<input type="submit" value="Next" />
</form>
<a href="addbook.php?up=<?php echo $inwardid; ?>"><button>Proceed</button>
You want to send the value the user typed in to the other page. So use this for your <form>:
<form method="POST" action="addbook.php">
<input name="up" type="text" id="up">
<input type="submit" value="Proceed">
</form>
To access the value in addbook.php, use $_POST['up'].
This will send the value the user typed in the input label (type="text") to the addbook.php page, using a $_POST. No need for a $_GET, $_POST will do just fine.
As you deliberately asked for method GET, my solution shows you GET!
You must know there is no security issue when using GET. It depends what you want to do. GET is useful if you want to use a dynamic code in multiple ways depending on some some variables that you do not want to hard-code in your script, or simply do not want to send files or other huge data.
Lets admit a newspaper has a site called breaking_news.php and you want to access the breaking news of November 8, 2016you could use this as :
breaking_news.php?y=2018&m=11&d=08
The fact that one can see your GET vars means nothing. Even by using POST one can see your variables by looking at your code. And one way or the other you must protect against code injection and brute force.
But if your not in the mood to show this vars to your visitor you can use URL rewriting to rewrite the url above in the browser as
RewriteRule ^breaking/(.*)/(.*)/(.*)/news\.html$ breaking_news.php?y=$1&m=$2&d=$3 [NC,L]
so you send your visitor to see the (rewritten)URL
breaking/2018/11/08/news.html
but what the web-server is showing him is:
breaking_news.php?y=2018&m=11&d=08
A reason to use this if for example when you want your dynamic site to be taken into consideration by some searching engine as a static site, and get indexed. But this is again another battle field.
Second, you want to send the variable to "addbook.php", and not to itself.
Your question sounded like you want to send to "another page" not to the same page.
Third, I can see in your code snippet you want to submit the variable "up" and not "inwardid", as you did in your code.
And also I can see you want the "submit" button to be called "Proceed".
Your code would look like this:
<form method="GET" enctype="application/x-www-form-urlencoded" action="addbook.php" target="_blank">
<input name="up" type="text" id="inwardid" />
<input type="submit" value="Proceed" />
</form>
As I said you must protect against injection, and this means for example, that in the "addbook.php",to whom you are sending the variables you must write some code that protects you against this issues. As your question is not in this direction I will not enter this subject.
To avoid problems with special chars you must "url-encode" your variable specially when sending them per POST method. In this case you must use this enctype if your handling text. Because this enc-type is transforming special chars into the corresponding ASCII HEX-Values.
Using GET your safe, because GET cant send in another enc-type. So your variable will automatically be url-encoded and you receive a string that is compliant to RFC 3986 similar by using:
rawurlencode($str)
Lets admit someone smart guy fills in a your input box the following code, in the desire to break your site. (This here is not exactly a dangerous code but it looks like those who are.)
<?php echo "\"?> sample code in c# and c++"; ?>
using enctype="application/x-www-form-urlencoded" this will become something like this:
%3C%3Fphp%20echo%20%22%5C%22%3F%3E%20sample%20code%20in%20c%23%20and%20c%2B%2B%22%3B%20%3F%3E
what makes it safe to be transported in a URL, and after receiving and cleaning it using
strip_tags(rawurldecode($_GET['str']))
it would output something like this, what is a harmless string.
sample code in c# and c++

echo back $array[] elements to html form on Submit

After alot of digging around some very informative posts and info to try and find out how to solve this issue I thought I would ask around to see if anyone has any pointers.
I have an html form with various inputs (checkboxes, text boxes etc...). Each input section has its own submit or 'Upload' button. On Upload a php script is called and various bits of processing is done before data is sent over a pipe to a Python script for further stuff.
I am currently echoing back input variables to the form on submission so that the html page does not refresh (or should I say the inputted data is not lost to the users view) on an Upload event, however, I now have to do the same for a bunch of checkboxes and text boxes the values of which are stored in an array. The code I have written so far is as follows (I am new to both php and html so please excuse the inefficiency that I'm sure is obvious)
html/php
<margin>CH1</margin><input type="checkbox"name="ANout[]"value="AN1_OUT"
<?php if(in_array('AN1_OUT',$_POST['ANout']))echo'checked';?>>
Voltage<input type="text"size="5"name="ANout[]"
value="<?php $ANout[$i]=$_POST['ANout'];
if(!empty($ANout[$i]))echo"$ANout[$i]";?>">
<br>
The code above works fine for the checkboxes which happily remain after an Upload button is pressed but not for the array. When the Upload event occurs I simply get 'Array' written in the text box. I have tried existing code I have written to echo back other text input in the form (see below) and which works but these are for sole entries, not arrays. I have tried various configurations of syntax but I always seem to get the same result.
Working Code:
<margin>Duty Cyle</margin><input type="text"name="PWM1DC"size="3"
value="<?php $PWM1DC = $_POST['PWM1DC'];
if(!empty($PWM1DC))echo "PWM1DC";?>">
<br>
I'm sure it is something straightforward but I have been fiddling and staring at it for ages and can't seem to find the problem.
You are getting "Array", because you are trying to print out variable of type Array.
You probably want to give your fields separate names or indexes and do something like this:
<form method="post">
<input type="checkbox" name="ANout[1]" value="AN1_OUT"
<?php if(isset($_POST['ANout']) && in_array('AN1_OUT',$_POST['ANout']))echo'checked';?>>
Voltage<input type="text"size="5"name="ANout[2]"
value="<?php if(isset($_POST['ANout']) && !empty($_POST['ANout'][2])) echo $_POST['ANout'][2]; ?>">
<input type="submit" value="ok">
</form>
(Just added form tags, submit button and isset checks to show working example.)

Submit same form to multiple locations without Javascript

Having looked at various similar questions, both on SO and elsewhere, I have a horrible feeling what I want to do is impossible, but here goes.
I have a page that is a table of text input rows. The user enters information on each row, and submits the data to a separate file, which creates a PDF.
The problem is that I need the user to be able to add rows to the table at will, since the amount of data can vary.
[Before you go there, I need to point out that I cannot use Javascript for any of this - I know it is easy to do in JS but the page needs to be accessible.]
Here is a very simplified version I just cobbled together to (hopefully) illustrate the point:
<?php
if (filter_has_var(INPUT_POST, 'add_rows')) {
$howmanyrows = filter_input(INPUT_POST, 'howmanyrows', FILTER_SANITIZE_NUMBER_INT);
//get all the data from table and put it in an array,
//then add 5 (or however many) new rows to said array.
}
else if (filter_has_var(INPUT_POST, 'send_data')) {
//get table data, add to session and redirect to other page with a header()
}
?>
<html>
<form action="" method="POST">
<table>
<?php //table rows added using an array of data
foreach ($data as $d): ?>
<tr><td><input type="text" value="<?php echo $d; ?>"></td></tr>
<?php endforeach; ?>
</table>
<input type="text" name="howmanyrows" value="5">
<input type="submit" name="add_rows">
<input type="submit" name="send_data">
</form>
...
</html>
As you can see, at the moment I have a clunky setup where there is just one form that encompasses the entire page, and submits the page to itself. Depending on the button that was clicked, a new row is added or the data is submitted to the PDF-creation page.
This is not ideal, for so many reasons. What I really want to be able to do is have two separate forms, or nested forms. But the former won't allow the input values to be submitted to both, and the latter is apparently bad form (no pun intended) and doesn't work.
Is it at all possible to make this do what I want it to do? Any suggestions for a different way to go about it?
I think you have the best non-javascript solution - certainly hte way I'd run with it.
One thing to make it easier is that you can use multiple inputs with the same name:
<input name="tablerow[]" type="text" value="A" />
<input name="tablerow[]" type="text" value="B" />
<input name="tablerow[]" type="text" value="C" />
And these come through the $_POST['tablerow'] as an array. The length of the array is the number of fields. Then add additional fields to that.
For accessibility, you should add a link at the top that allows the user to hop directly to the first "new" field - otherwise they need to tab through the entire form to get to the new field. (See my comment above about if JS is really unavoidable as you and they can avoid this scenario!)

Using javascript and $_SESSION's to record wanted user information over pagination

What I have so far is a paginated page, showing all users in a database system. Each page shows 30 users and has a checkbox next to each user, what I need is a way for users to select and deselect these users and for these selections to propagate through, so if the user goes back to page 1 from page 2, all users from page 1 will still be checked.
I also need a way to record this information, so that once the user has looked at all the pages and clicks a submit form all checked users information can be processed. I am thinking of using javascript to record the information and php sessions to store it, but with the way I am trying now, when a user clicks a checkbox, it is not ticked.
Does anyone have a better way of doing this/see how I can fix this problem?
Thanks.
<script type="text/javascript">
function log_export($str) {
document.check.data.value = $str;
document.check.submit();
}
</script>
<?php
if(isset($_POST['data'])) {
echo $_POST['data'];
}
?>
<form name="check" method = "post" action = "">
<input type="hidden" name="data">
<input type="checkbox" name="A" onclick="log_export('1')" />
<input type="checkbox" name="B" onclick="log_export('2')" />
<input type="checkbox" name="C" onclick="log_export('3')" />
</form>
Few ways you could do this, but I'd avoid using javascript to do it. You could use an array in your $_SESSION to keep the list across pages.
<form name="check" method = "post" action = "">
<input type="checkbox" name="person[A]" />
</form>
(note: The form elements are named person[A], person[B]...etc, so they can be accessed as an array in php and make your life easier.)
Then in the php you can store this in the session...
$_SESSION['saved_list'] = $_REQUEST['person'];
This way the session variable saved_list will contain the array person with all the checked boxes in it. You'll need to be careful not to overwrite the array each time however, so adding...
$_REQUEST['person'] = array_merge($_SESSION['saved_list'], $_REQUEST['person']);
...before this should keep them (if I'm remembering my merge functions correctly).
Alternatively, you could just use html to save the checkboxes already ticked. When page 2 receives the results from page 1, it could print them out as hidden elements at the end of the page 2 form. This way they can exist across pages, however this could become a bit unwieldy with 30 names a page.
I'd suggest storing it in a php session array, this shouldnt really involve using Javascript, it just over-complicates matters.
Why you don't change your form method to GET and make the pagination link so it contains every parameters passed to the form and the page number. I think it make everything more simple to handle that case with parameters passed on the URL against posted one.
you can create those links like this:
for ($i =0; $i < $max_page; $i++){
echo "{$_SERVER['REQUEST_URI']}?$_SERVER['QUERY_STRING']&p={$i}";
and you just have to change your backend to use $_GET instead of $_POST.

Very quick, easy, webpage with increment/decrement

I'm looking for any direction on a really quick and dirty webpage. I'm going to have two static items, say person A and person B. I would like to click a (+) or (-) button next to each of them which then increments or decrements an integer that's displayed relative to each person.
Anyone having a quick tut or anything would be useful.
Aside from this, how hard would it be to keep a viewable log of each time the value was altered either incremented or decremented, would it be easy to add in date/time to that?
Edit
Alright, concerning mysql. I have a db already setup from a previous wordpress installation. I'm going to create a new tables named 'points', should this have 2 fields? One for a person A and one for a person B?
Since you want it to remember the value between sessions (ie- if I incremented the counter, left the website, and came back, I expect it to still be incremented) you need to store the value server-side. Databases are the best recommendation for this.
If you're planning to use PHP (which I assume from the tags), then MySQL is one of the easiest databases to implement. If you already have a MySQL database set up at your host, then this will be easy. If not, how to set up a MySQL database will be another question you need to ask.
Since you want quick and dirty the best method would be a form. Either POST or GET (preferably GET if you want people to send a "vote up this image" link, preferably POST if you don't want such links to be possible). This is easy, but it also requires reloading the page which is why modern voting systems use AJAX calls (javascript).
Your HTML form would look something like this:
<!-- Person A goes here -->
This person has a score of <!-- We'll do this soon -->.
<form method="get" <!-- or post --> action="vote.php">
<input type="submit" name="submit_button" value="Vote Up!" />
<input type="submit" name="submit_button" value="Vote Down =(" />
<input type="hidden" name="person" value="A" />
</form>
<!-- Similar for person B -->
Note that <!-- --> is the syntax for an HTML comment (these will be removed in the final website)
In vote.php you would need to first see if the form was submitted, then see WHICH submit button was pressed (vote up or down), then see which person it applies to. Then we do our database entry.
<?php
if(isset($_GET['submit_button'])){
// They submit the form
$add = ($_GET['submit_button'] == 'Vote Up!') ? 1 : -1;
$person = $_GET['person'];
$link = mysql_connect('localhost', 'user', 'password');
mysql_select_db('database', $link);
mysql_query("UPDATE table SET value=value+$add WHERE person=$person");
} else {
die("You didn't submit the form =(");
}
?>
Mind you this is a REALLY dirty method (there is no parsing of the query and no checks made. This is very susceptible to an SQL injection. Do NOT use this in a database with important information. In fact- probably don't use this at all without a few changes =) )
Now then, this basically takes the table table, finds the entry where person equals whatever person was selected (chosen by which form was used to submit), then adds either +1 or -1 to value. You can change any of these variable names in your own table. The next step: reading the value to display on the previous page. Remember that before I just had the comment <!-- we'll do this soon -->. We'll get to that now.
In the beginning of your first page you want to read the database. This means your first page must also be PHP.
<?php
$link = mysql_connect('localhost', 'user', 'password');
mysql_select_db('database', $link);
$result = mysql_query("SELECT value FROM table WHERE person=A");
...
Now you have a MySQL resource, but you need the value out of it.
...
$row = mysql_fetch_row($result);
...
And now we display it with the information.
<!-- Person A goes here -->
This person has a score of <?php echo $row[0]; ?>.
<form method="get" <!-- or post --> action="vote.php">
<input type="submit" name="submit_button" value="Vote Up!" />
<input type="submit" name="submit_button" value="Vote Down =(" />
<input type="hidden" name="person" value="A" />
</form>
Then you repeat for person B. This is really the dirtiest method since it involves one call to the database per person. Ideally you'd grab all values you want in a single call and then iterate over the returned resource and determine who was who. Or, if you really wanted to be fancy, you could already know who was who by using SORT ASC =)
Like I said, though, this is the quickest, easiest, and dirtiest method to do what you want using PHP and MySQL.
Anyway I'd go for the database storing of person data and increment by id .
This is the flow for it :
Create mysql or mysqli database "person", create table "rates" id - autoincrement
rate will be integer.
Create php file with database connection and the functions related to it.
you can use same file to create increment function, when row is the result from the integer relative to this entry :
$rate = $row['rate'];
function incvar(){
global $rate;
if(isset($rate) || $rate>0){
return $rate++;
}
}
function decvar(){
global $rate;
if(isset($rate) || $rate>0){
return $rate--;
}
}
Now create query updating existing fields with results from those functions.
Ideally is to create ajax request onclick to this file to increase and decrease the integer. For fast execution use jquery.

Categories