Cant get $_POST values from multiple forms - php

i got a bit of a problem, as you guys can see in my code, i got a foreach looping through my img folder, showing all the images, well i left out the proper styling of the images, since the problem is the form inside every image.
i need to get the value from the radio input, so i can tell my other script to select all the info from the DB where the ID has the same value as the input.
and i needed a if statement so that if nothing is set i can show something saying you need to select a radio before you can listen to any stations.
but my if statement keeps showing 'error', even tho i click on the buttons
i hope anyone could help me out :)
if(isset($_POST['submitRadio')):
$test = $_POST['radio'];
echo $test;
else:
echo 'error';
endif;
foreach(glob('img/radios/big/*.png') as path):
printf('
<form method="post">
<input class="hidden" type="text" name="radio" value="1">
<input type="submit" name="submitRadio" value="Go!">
</form>
');
endforeach;
after doing what GolezTrol told me to do:
<div class="row text-center">
<?php
$sql = "SELECT * FROM radio";
$stmt = $Db->dbh->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
if(isset($_POST['submitRadio'])):
$test = $_POST['submitRadio'];
echo $test;
else:
echo 'error';
endif;
?>
<form method="post">
<?
foreach($result as $radio):
printf('
<button type="submit"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
?>
</form>

I've removed my previous solution. I only just saw that you have no actual radio button but hidden elements, so basically the buttons are the radios.
That changes it a little bit because you actually have the alternative suggestion I proposed earlier: The buttons themselves work as radiobuttons that immediately post the chosen option.
To solve your issue, you can use a button instead of an input for submitting the form. In a button, you can make the caption and the value differ from each other, so you can just put the id (or filename, or whatever you need) in the value of the button and don't need the hidden input at all. The content of the button tag is the caption it gets, so the code can look like this:
if(isset($_POST['selectedFile')):
$test = $_POST['selectedFile'];
echo $test;
else:
echo 'error';
endif;
?><form method="post"><? // Open the form outside of the loop
foreach(glob('img/radios/big/*.png') as path):
// Not sure what you want to do here. Put the filename instead of
// "1" in the value?
$filename = basename($path, '.png');
?>
<button type="submit"
name="selectedFile"
value="<?=$filename?>">
Go!
</button>
<?
endforeach;
?></form><? // Close the form
In this example I've pulled the form tags out of the loop, because strictly you only need one form. But since there are now no radiobuttons at all, you could also have one form per button. It would still work.
By the way, I saw you mentioned a database in your comment. Of course I didn't take that into account, since you didn't mention that in the question. Anyway, it shouldn't change the basic concept, only the way the 'value' is determined.

First, the value code in radio tag is always 1. So if any radio button is selected, you will always gets 1. Instead the value clause should have the filename. So you get to know which image (radio button) is selected.
For none of the image (radio button) selected, you may use
if (!isset($_POST['radio']))<br>{<br>//php code }

Related

I want to create buttons dynamically and acces any specific

I want to show buttons depending on the values from a table. Afterwards I need to access anyone button and act according to the label of buttons. To be more specific, i have a table containing names of subjects, I want to show the buttons each having label of a subject. when user clicks a button (eg: Physics), the screen should display a test (MCQs) of Physics only, and so on:
Below is my code:
<button id="subj" onclick="showSubjects()">Start Test </button>
<div id="subjects" style="display: none;">
<form method='POST'>
<?php include_once('connect.php');
$query = "select distinct subject from subjects order by subject
desc ";
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_array($result)){
$subjectname = $row['subject'];?>
<input type="submit" id = "sub" name="sub"
value='<?php echo $subjectname; ?>'>
<?php } ?>
</form>
</div>
<?php
if(isset($_POST['sub'])){echo $subjectname; } else {echo
"Nothing";}
?>
</body>
<script type="text/javascript">
function showSubjects(){
document.getElementById("subjects").style.display = "block";}
function showTest(){
document.getElementById("tests").style.display = "block";
} </script>
This shows 3 buttons: PHISICS CHEMISTRY BIOLOGY
when user clicks any of these buttons it takes it as last button value i.e. BIOLOGY.
How can I amend it so that if user clicks CHEMISTRY it should show "Chemistry button clicked" and so on
The only thing that will change based on the submitted form is the $_POST array. Other variables, like $subject, will be the same whatever the user does; PHP isn't going to guess what you want them to be.
You've already got logic checking if the user pressed any button:
if(isset($_POST['sub'])){ ... }
Determining which button they pressed is just a matter of looking at that same variable:
echo $_POST['sub'];
The same goes for any other form controls you add - the user's selections will end up in $_POST, and it's up to you to read them from there.
It's also worth remembering that the logic for displaying the form doesn't need to be in the same place as the logic for precessing the submitted form, so the fact that these buttons are generated dynamically doesn't make a difference to how you read the submitted data back. You can't even guarantee that the user used your form at all, they could write their own and submit it to your server, or edit it using their browser's debugging tools.

One submit button to send form data to one PHP destination OR another

I' new to HTML and PHP and was wondering if anyone out there could help me with a question... I'm trying to code a form that submits a selection from one menu OR another and, depending on which is chosen sends the data to one of two different PHP pages.
<form id="form1" method="post" action="">
<label for="SubjectID">Text Books by Subject</label>
</p>
<p>
<select "name="SubjectID" id="SubjectID">
<?php do { ?>
<option value="<?php echo $row_rsSubject['SubjectID']?>"><?php echo $row_rsSubject['SubjectName']?></option>
<?php } while ($row_rsSubject = mysql_fetch_assoc($rsSubject));
$rows = mysql_num_rows($rsSubject);
if($rows > 0) {
mysql_data_seek($rsSubject, 0);
$row_rsSubject = mysql_fetch_assoc($rsSubject);
} ?>
</select>
</p>
<p>
——— OR ———
</p>
<p>
<select name="CourseID" id="CourseID">
<?php do { ?>
<option value="<?php echo $row_rsCourse['CourseID']?>"><?php echo $row_rsCourse['CourseID']?></option>
<?php } while ($row_rsCourse = mysql_fetch_assoc($rsCourse));
$rows = mysql_num_rows($rsCourse);
if($rows > 0) {
mysql_data_seek($rsCourse, 0);
$row_rsCourse = mysql_fetch_assoc($rsCourse);
} ?>
</select>
</p>
<p>
<label for="CourseID">Text Books by Course</label>
</form>
So, the action should be (depending on which menu the user selects from) that the form submits to either subject.php or course.php, and I can't figure out how to do that with a single submit button. Can anyone help me?
first set onchange event to select:
<select name="CourseID" id="CourseID" onchange='myFunc(this)'>
Then:
<script>
function myFunc(element){
// set the form action depends on option chosen
// element.setAttribute('action', 'yourPageLink' );
}
</script>
You could update the action attribute with javascript when the user changes his selection, directing him to the relevant page.
Otherwise, why not submit to a single function and depending on the users selection call the relevant function?
Honestly I would use jquery's $.post to do this. To the best of my knowledge you can't really do that with straight html, and php is executed before the page loads so that's no help. With JQuery you could set an action to the button to call a function. Then your function could check the value of the select and pass the proper url to the $.post function.
You can read about that particular jquery function here: http://api.jquery.com/jQuery.post/
If you're not familiar with JQuery it's really easy to use with just a bit of reading if you're good with JavaScript.
Why not have a radio button in the form whose posted form value is processed by a central PHP form handler? That way, depending on what is entered on the radio button, you can process the request as necessary.
This might not be the answer you are looking for, but I am not clear if you want the user to be able to alter the destination or what.

$_POST, image forms and mysql.How to get them working together?

I'm trying to get a website working. What I have are basically two images displayed (random, taken out of a mySQL database). What I need to do is (when the user clicks one of the images) the following:
Update the page, passing the info about the selected image (submit form);
Add one piece of data to the database (upvote the image)
I need to use $_POST to pass an array of values to the next page. So I thought:
<form name="input" action="the_page.php" method="POST">
<input type="image"
name="img"
src="image.png"
value ="dat1[\"data1\",\"data2\",\"data3\"]">
<!-- If value must be a single string, I'll use hidden inputs-->
</form>
<form name="input" action="the_page.php" method="POST">
<input type="image"
name="img"
src="image2.png"
value ="dat2[\"data1\",\"data2\",\"data3\"]">
</form>
Then I can upvote the selected image on the mySQL database with a little php upvote() function that updates the record. The upvoting process is done when the new page is loaded. From this, I have a couple questions:
I'm guessing the images will act as buttons, right? (They are supposed to submit the form, hence refreshing the page). If not, how can I achieve this? I'm unable to do it with a link (since I can't add the values to it). Maybe a javascript function? But I don't know how to submit the form that way either...
Once the page is reloaded, does it mean that only the data from one form has been submited, so I can retrieve the data by simply calling the PHP variable $_POST['img'] and get an array back?
EDIT: I now managed to get everything working, slightly similar to what I proposed initially. Thanks for the AJAX suggestion though, since it was what helped me solve it (looked up AJAX tutorials, found solution).
Here's my solution:
<?php
echo "<form name=\"input\" action=\"F2F.php\" method=\"POST\">";
echo "<input type=\"hidden\" name =\"table\" value=\"".$table1."\">";
echo "<input type=\"image\" name=\"nom\" src=\"".$IMG_Route1."\" value =\"".$Nom_base1."\" border=\"0\">";
echo "</form>";
?>
(where the image goes)
and then, on the header:
<?php
if ($_POST['nom']||$_POST['nom_x']){
if (!$_POST['nom']){
echo 'Could not retrieve name. $_POST[\'nom_x\'] = '.$_POST['nom_x']. mysql_error();
exit;
}
if (!$_POST['table']){
echo 'Could not retrieve table. $_POST[\'table\'] = '.$_POST['table']. mysql_error();
exit;
}
upvote($_POST['table'],$_POST['nom']);
}
?>
You can use one form and a set of radio buttons to simplify things a bit. Clicking on the label will toggle the radio button. You can use commas to separate multiple values for each checkbox, which you can then abstract later on (see below)
<form name="input" action="the_page.php" method="POST">
<ul>
<li>
<label>
<img src="whatever.jpg" />
<input type="radio" name="selectedImage" id="img1" value="12,16,19" />
</label>
</li>
<li>
<label>
<img src="whatever2.jpg" />
<input type="radio" name="selectedImage" id="img2" value="12,16,19" />
</label>
</li>
</ul>
</form>
You can detect when the radio button is selected by adding a listener for the change event, then submit the form.
$('input[name="selectedImage"]').change(function() {
$('form[name="input"]').submit();
});
To abstract the multiple values, you can then explode the form result with PHP, which will return an array of the values.
$selectedImageValues = array();
$selectedImageValues = explode(",", $_POST['selectedImage']);
From there you can pull the different values out and save the data to the database.

isset for link - PHP

I'm attempting to create a link for users to click that will remove them from a list. I'm trying to figure out how to do this without using a submit button and without using $_GET(if possible).
Anyway, I'm afraid to do it with $_GET (the way I have it now), because the user can type this in the URL (even though 99% wouldn't know how or think to do this) and they would be removed from the list.
How can I name the link so I can use $_POST?
$attendingUsers = mysql_query("Select acceptedInvites from events where eventID = ".mysql_real_escape_string($_GET['eventID'])." ");
$users= mysql_fetch_array($attendingUsers);
$user = $users['acceptedInvites'];
if(preg_match("/$userid/", $user)){
echo "You are attending this event</br>";
echo 'Click here to remove yourself from the list';
if($_GET['delete']=1){
$sql=...
}
}
Is it possible to do this without using $_GET? Thanks!
Never delete via a link. Read The Spider of Doom
Best way is to link to a "delete" page with an "are you sure" form. Submitting the form (via POST) performs the delete and redirects back to a suitable results page.
For example
Click here
to remove yourself from the list
Then, in remove.php
<?php
// get Event details via $_GET['eventID']
if (isset($_POST['confirm'])) {
// delete via SQL
// redirect
header('Location: http://example.com/events.php');
exit;
}
// display event details
?>
<form method="post" action="remove.php?eventID=<?php echo $eventId ?>">
<p>Are you sure?</p>
<input type="submit" name="confirm" value="Remove me from this event">
</form>
You should probably also look into CSRF protection but that's really outside the scope of this question.
Your are required to use either $_GET or $_POST
<form action="delete.php" method="post">
<input type="hidden" name="eventId" value="yourEventId" />
<a href="#" onclick="this.form.submit();" > Delete</a>
</form>
If I have my JavaScript right, this should do the trick:
Delete
<form id="delete" action="delete.php" method="post">
...
</form>
The link will then submit the form.
You could use some kind of encoding to make the get var unreadable, like an md5 or even an encrypted string.

Get option value AND text with PHP

Let's say I have a HTML form:
USA
CDN
And I select option 1 (USA)
Then a php page
Ok, duh, works fine and echo's "1"
How can I display "USA" as well? So in essence, I want to pass along the option's TEXT also. How could I do this?
You would either need to change the option value on the HTML page to be the text you want displayed (poses a XSS security hazard) or on the page that's displaying the text, you'd need an array where all the values match with the forum input.
Ex:
$names[1] = "USA"; $names[2] = "CDN";
Then when you want to display it, you'd call $names[$selection] to output the text.
Another option you can consider is using javascript to update a hidden HTML element on the submitting page when the user makes their selection (using onUpdate). This information would be passed along with the submitted form data. Not the most secure or reliable of options, but an option nonetheless.
The client's browser will not post back anything beyond the form element's name and value - you would have to incorporate additional form fields and Javascript (or change the element's value) to post "USA".
I suggest having a copy of the same data structure you used to print the form.
For example, if you were to do it all in one PHP page...
<?php
$countries=array('USA','CDN');
?>
<form action='?' method='post'>
<select name='country'><?php
foreach($countries as $key=>$country){?>
<option value='<?php echo $key;?>'><?php echo $country;?></option>
<?php
} ?>
</select>
<input type='submit'>
</form>
<?php
if(isset($_POST['country'])){
$chosen=(int)$_POST['country'];
if(!isset($countries[$chosen])){?>Unknown country selection, wtf<?php exit; }?>
<div style='margin-top:20px;'>You selected <?php echo $countries[$chosen];?></div>
<?php }
Another option is to ditch the numeric value altogether, and just use the country name as the value of the option. However, for verification, you'll still want the list of values. Check the differences in this example...
<?php
$countries=array('USA','CDN');
?>
<form action='?' method='post'>
<select name='country'><?php
foreach($countries as $country){?>
<option value='<?php echo $country;?>'><?php echo $country;?></option>
<?php
} ?>
</select>
<input type='submit'>
</form>
<?php
if(isset($_POST['country'])){
$chosen=preg_replace('/[^\w]/','',$_POST['country']);//this isn't strictly necessary, since the next line checks if the value is in your original array - but filtering input is a good habit!
if(!in_array($_POST['country'],$countries)){?>Unknown country selection, wtf<?php exit; }?>
<div style='margin-top:20px;'>You selected <?php echo $chosen;?></div>
<?php }

Categories