PhP Radio button in Array - php

I have a form where you can select a radio button and it should transfer what was selected to the next page. My problem is that no matter which radio button you choose it always transfers the value associated last radio button over instead of the one you chose.
So if I choose Around the World it carries 5 with it instead of 10
I am required to use the GET method.
Here is my code:
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
}
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
This is the code for the next page:
echo "<b>$sub</b><br />";
echo "Base Total: $ $s_value/mon x $month months <br />";
Yes I have omitted a lot of things, because everything else in my code is fine.
I tried doing this as well, adding in an unset() statement but it didnt work. It completely deleted the value variable....
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
unset($s_value);
}
//I also tried putting the unset here//
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}

You need to change the names of your variables $s & $s_value within the foreach loop. The foreach loop is setting these variables and they are then being accessed outside of the foreach loop if either of the GET values is empty such that there is no GET value to replace the contents of the variable. Therefore, it always uses 5 as the value because that is the last $s_value that you set.
In summary, changing $s & $s_value within the foreach loop to something like $key & $value respectively will fix your problem with the array value. Alternatively, you could unset them after the foreach loop but before the if statements.

In your current code, you just happened to switched the values on the loop. 10, 7, 5 are inside the elements, while the names Around The world... etc are inside the keys. You just need to switch them. Consider this example:
<?php
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
if(isset($_GET['submit'], $_GET['sub'])) {
$sub = $_GET['sub'];
$name = array_search($sub, $title);
echo '<script>alert("You selected '.$name. ' => '.$sub.'");</script>';
}
?>
<form method="GET" action="index.php">
<?php foreach($title as $key => $value): ?>
<input type="radio" name="sub" value="<?php echo $value; ?>" /> <?php echo $key; ?> <br/>
<?php endforeach; ?>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>

Related

form does not get through POST

$product = '';
$stmt = $verbinding->query("SELECT
product_category, product_id, parent FROM
Productcategory ORDER BY product_category");
$categorien = $stmt->fetchAll();
foreach($categorien as $cats){
if($cats['parent'] === $producten){
echo '<form action="product-list.php" method="post">
<input type="submit" name="cats" value="'. $cats['product_category'] .'"></form>';
echo $producten;
//var_dump($_POST);
if(isset($_POST['cats'])){
echo $_POST['cats'];
echo $cats['product_category'];
echo $cats['product_id'];
if($_POST['cats'] === $cats['product_category']){
$product = $cats['product_id'];
echo $product;
echo "gelukt!!";
}
}
}
}
So to update my question this is code that does partly work but does not get past the if($_POST['cats'] === $cats['product_id']){ statement. The problem is that my $_POST['cats'] just sends NO information. I can't understand why though. I should say though that I use the same "name" value in another form, but if I don't it wont even go through the if(isset($_POST['cats'])){ statement.
From your form the action page is "product-list.php", is it the same page you are handling the form logic in?
If not then your you need to write the code below in the product-list.php you created.
....
if(isset($_POST['categorien'])){
echo "pastcategory?";
if($_POST['categorien'] === $cat['product_category']){
$producten = $cat['product_id'];
echo "pastcategory!!!!";
echo $producten;
}
}
....

How to add GET and remove

I have more GET variables. I want the variables to be added after clicking. And after clicking again I want them to be removed from GET. I am a beginner and I don't know how to do it.
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url=$_SERVER[QUERY_STRING];
if(!empty($url)){
$url="&".$url;
}
?>
<form action="" method="GET">
<?php
foreach($tab_array as $key => $val){
?>
<?php echo $key;?>
<?php
}
?>
</form>
Someone will help?
Sorry for my bad English...
Code
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url='?'; // this will call the current url
// $_GET is the array your submitted data will be strored in - initially empty []
?>
<form method='GET'><!-- you actually don't need a form, since only input, textarea, etc get submitted -->
<?php
// save current state, so you can modify it for every possible click
$current_get = $_GET;
foreach($tab_array as $key => $value) {
$new_get = $current_get;
// check if the current key is already in your set ($new_get)
if (array_key_exists($key, $new_get)) { // it is, so remove
unset($new_get[$key]);
} else { // it is not, so add
$new_get[$key] = $value;
}
// build your query_string (from $new_get array)
$query_string = http_build_query($new_get);
// you can use variables in string when its encapsulated in double quotes: "text $var"
echo "<a href='$url$query_string'>$key</a>";
// more readable:
// echo "<a href='{$url}{$query_string}'>{$key}</a>";
// not need but looks better :P
echo '<br />' . PHP_EOL;
}
?>
</form>
A little more
there is a shortcut for <php echo $var ?> which is just <?= $var ?>
Links
array_key_exists
unset
http_build_query

Trying to echo condition by given input but results are three times I want single result condition by given input

**hi here is the code please answer my question. I'm trying to echo condition by given input but results are three times I want single result condition by given input **
<?php
$arrayName = array('bravo', 'alpha', 'jhony');
foreach ($arrayName as $key) {
if (isset($_REQUEST['num1']) && $_REQUEST['num1'] == $key) {
echo "yes". $_REQUEST['num1']. "Available";
} else {
echo "Sorry!".$_REQUEST['num1']." is not available";
}
}
?>
<form action="" method="get" accept-charset="utf-8">
<input type="text" name="num1">
<button type="submit">submit</button></form>
Rather than loop through your white list, use in_array:
$arrayName = array('bravo','alpha','jhony' );
if(isset($_REQUEST['num1']) && in_array($_REQUEST['num1'], $key)){
echo "yes". $_REQUEST['num1']. "Available";
}
else{
echo "Sorry!".$_REQUEST['num1']." is not available";
}

Replace isset for each $_POST using foreach

I've been trying to replace each isset for $_POST(s) using foreach.
This is the real code using isset for each $_POST :
<form method='post'>
<input type='text' name='name'> <br>
<input type='text' name='address'> <br>
<input type='submit' name='send'>
</form>
<?php
if (isset($_POST['name']) && isset($_POST['address']) && isset($_POST['send']))
{
echo "All elements have been submitted";
}
else
{
echo "You forget some elements, try checking name or address";
}
?>
is there a way I can replace 4 isset(s) above with single isset using for each?
I've made this and it goes wrong.
<form method='post'>
<input type='text' name='nama'> <br>
<input type='text' name='alamat'> <br>
<input type='submit' name='kirim'>
</form>
<?php
foreach($_POST as $value)
{
if (isset($value))
{
echo "All elements have been submitted";
}
else
{
echo "You forget some elements, try checking name or address";
}
}
?>
Need help guys, It's just wasting of time if I have to write isset one by one for each element I send via post / get. I've seen something like this before in visual basic, my friend made an foreach construct to validate all textboxes in a form, so he didn't need to create something like this anymore :
if textbox1.text="" && textbox.2.text="" and so on
EDIT: jbrahy just had a typo. His answer is good now.
I think jbrahy's approach is the right general idea... but I don't think it actually works.
I'd do this.
$requiredFields = ["nama","alamat","kirim"];
$allElementsSet = true;
foreach ($requiredFields as $requiredField)
{
if (!isset($_POST[$requiredField]))
{
$allElementsSet = false;
break;
}
}
if ($allElementsSet)
{
echo "All elements have been submitted";
} else {
echo "You forget some elements, try checking name or address";
}
$_POST will only have the variables that are passed in and there are HTML elements that might not be passed in by just submitting. It's probably best to create a $required_fields array and even better if you can get some field validation but that's not what you asked for here. You'll want to take the key and value of $_POST.
$required_fields = array("name" => FALSE, "alamat" => FALSE, "kirim" => FALSE);
foreach ($required_fields as $key => $value){
if (isset($_POST[$key])){
$required_fields[$key] = TRUE;
}
}
foreach ($required_fields as $key => $value){
if (!$required_fields[$key]){
echo "Missing value for " . $key;
}
}
if you are trying to figure out if every key that is passed in has a value then something like this would work also.
foreach ($_POST as $key => $value){
if ($value == ""){
echo "Value(s) are missing";
break;
}
}

select all checkboxes if none are select in php query

I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!

Categories