i have a form with different checkbox fields. However, I was able to display their values using a foreach loop but was wondering if it possible to display them via how they are selected. below is my code.
<html>
<head></head>
<body>
<form action="states.php" method="post">
Draft<input type="checkbox" name="states[]" id="design_states" value="Draft">
Design<input type="checkbox" name="states[]" id="design_states" value="design">
Review<input type="checkbox" name="states[]" id="design_states" value="Review">
Approved<input type="checkbox" name="states[]" id="design_states" value="Approved">
Issued For Construction<input type="checkbox" name="states[]" id="color" value="Issued For Construction">
<input type="submit" value="submit">
</form>
<body>
</html>
<?php
if(isset($_POST['states'])) {
$name = $_POST['states'];
echo "You chose the following workflow: <br>";
foreach ($name as $states){
echo $states."<br />";
}} // end brace for if(isset
else {
echo "You did not choose a workflow.";
}
?>
if a user picks issued for construction first followed by draft I want that values to be displayed as picked not draft first and then issued for construction.
echo "You chose the following workflow: <br>";
foreach (array_intersect($states, $name) as $state){
echo $state."<br />";
}
echo "You don't chose the following workflow: <br>";
foreach (array_diff($states, $name) as $state){
echo $state."<br />";
}
Related
I am new to PHP coding. I have different preferences for the user to select from my html page. I want to retrieve all the check boxes selected by the user and display the hotel names which have all those preferences in them. For example if a user selects "Roof top", "Sea side" and "Swimming pool" check boxes, then the hotels against which their is a 1 placed in the respective columns in the mytrip.db database must be retrieved all at once and get displayed. My code takes only one checkbox value and displays the hotel name against that only. I want to display the hotels that contain all the preferences.
My code is below:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css" />
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<form action="php_checkbox.php" method="post">
<label class="heading">Select Your Preferences:</label>
<input type="checkbox" name="check_list[]" value="Swimming pool"><label>Swimming pool</label>
<input type="checkbox" name="check_list[]" value="Roof top"><label>Roof top</label>
<input type="checkbox" name="check_list[]" value="Sea side"><label>Sea side</label>
<input type="submit" name="submit" Value="Submit"/>
</html>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
checkbox_value.php code is below:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
$prefarray=array();
$i=0;
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected) {
$prefarray[$i]= $selected;
echo "<p>".$prefarray[$i] ."</p>";
echo "<p>".$selected ."</p>";
$i++;
}
echo "<p>".$i ."</p>";
$sql =<<<EOF
SELECT hotel_name from Dubai WHERE $prefarray[i]==1 AND $prefarray[i-1]==1 ;
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
?>
The problem with this code is that it only displays one checkbox value if I use query
SELECT hotel_name FROM Dubai WHERE $selected==1
I tried to save the check box values selected by making an array "prefarray". But when I execute the query that I have posted in my checkbox_value.php code it gives me error of "Undefined offset 3 in prefarray". I want the data base query to have only those checkbox values that have been selected by the user. For example if the user has selected 2 out of three checkboxes then my query should look like
SELECT hotel_name FROM Dubai WHERE $checkbox==1 AND $checkbox2==1;
Any help to achieve two of these tasks will be appreciated!
I have fixed and refactored (couldn't stop myself) your code.
I have changed column names to proper ones. There was some redundant code which did nothing so I got rid of it. The main thing you were looking for is concatenating each chosen column in foreach loop. I'm also checking selected values against hard coded $hotelOptions for protection against sql injection.
Here is what I got:
checkbox_value.php:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$hotelOptions = array('swimming_pool', 'roof_top', 'sea_side');
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list']) && is_array($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
$where = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, $hotelOptions) !== false) {
$where .= " AND {$selected} = 1";
}
}
$where = substr($where, 5, strlen($where));
$sql = "SELECT hotel_name FROM Dubai WHERE {$where};";
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
} else {
echo "<b>Please Select Atleast One Option.</b>";
}
}
html layout:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css"/>
</head>
<body>
<div class="container">
<div class="main">
<form action="checkbox_value.php" method="post">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<p class="heading">Select Your Preferences:</p>
<input type="checkbox" name="check_list[]" value="swimming_pool" id="checkbox_1">
<label for="checkbox_1">Swimming pool</label>
<input type="checkbox" name="check_list[]" value="roof_top" id="checkbox_2">
<label for="checkbox_2">Roof top</label>
<input type="checkbox" name="check_list[]" value="sea_side" id="checkbox_3">
<label for="checkbox_3">Sea side</label>
<div>
<input type="submit" name="submit" Value="Submit"/>
</div>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
I am making a site with checkboxes for toppings on pizza.
I have the problem that whenever I select one topping it does show and image of that topping but if I select two toppings it still only shows one image.
How can I make it so that it echoes the images of multiple checkboxes?
This is my index.php for the checkboxes and values:
<html>
<head>
</head>
<body>
<form action="process.php" method="POST">
<h4>Kies een Pizza:</h4><br>
<input type="checkbox" name="check[]" value="Pepperoni">Pepperoni<br>
<input type="checkbox" name="check[]" value="Ananas">Ananas<br>
<input type="checkbox" name="check[]" value="Ansjovis">Ansjovis<br>
<input type="checkbox" name="check[]" value="Broccoli">Broccoli<br>
<h4>Kies een bodem:</h4><br><br>
Megadik: <input type="radio" name="bodem" value="Megadik"><br>
Dun: <input type="radio" name="bodem" value="Dun"><br>
Calzone: <input type="radio" name="bodem" value="Calzone"><br>
</p>
<p>
<input type="submit" name="submit[]" value="Koop Pizza">
</p>
</form>
<br/><br/>
Home
</body>
</html>
And this is my process.php where it needs to happen:
<html>
<?php
if(isset($_POST['bodem']) && ($_POST['check'])){
$bodem = $_POST["bodem"];
echo("Je koos een pizza met:<br/> ");
}
else{
echo("Geen pizza gekozen!");
}
$selected_radio = $_POST['bodem'];
if(isset($_POST['submit'])){}
if(!empty($_POST['check'])){}
foreach($_POST['check'] as $selected){
echo $selected."</br>";
}
//Toppings
if (($selected == 'Pepperoni')) {
echo "<IMG SRC=\"pepperoni.jpg\">";
}
if (($selected == 'Ananas')) {
echo "<IMG SRC=\"ananas.jpg\">";
}
if (($selected == 'Ansjovis')) {
echo "<IMG SRC=\"ansjovis.jpg\">";
}
if (($selected == 'Broccoli')) {
echo "<IMG SRC=\"broccoli.jpg\">";
}
//Bodems
if(($selected_radio == 'Megadik')) {
echo ("<p>En de bodem Megadik</p>");
echo "<IMG SRC=\"megadik.jpg\">";
}
if(($selected_radio == 'Dun')) {
echo ("<p>En de bodem Dun</p>");
echo "<IMG SRC=\"dun.jpg\">";
}
if(($selected_radio == 'Calzone')) {
echo ("<p>En de bodem Calzone</p>");
echo "<IMG SRC=\"calzone.png\">";
}
?>
<br/><br/>
Home
</html>
Im sorry its in Dutch.
The value of $selected is updated each iteration of the loop. Then when the loop is done it will keep the last value. It will not "remember" all the values it had while looping. So you need to echo the img tag in the loop (or, if you want them separately somewhere else, in another loop).
Also, you can shorten the code by not having an if clause per topping, but instead using the fact that the file names of the images correspond to the topping names.
Then you get something like this:
foreach($_POST['check'] as $selected) {
echo $selected . "</br>";
echo "<img src=\"" . $selected . ".jpg\">";
}
Or if you want the separately:
foreach($_POST['check'] as $selected) {
echo $selected . "</br>";
}
//Some other stuff...
foreach($_POST['check'] as $selected) {
echo "<img src=\"" . $selected . ".jpg\">";
}
Please note that is is recommended to write HTML tags in lowercase.
What happens when this piece of code executes:
foreach ($_POST['check'] as $selected){
echo $selected."</br>";
}
On each iteration you echo the value. But when foreach is over $selected value is the last value of $_POST['check']. So, only your last value is checked against you if statements.
So the answer is - move your if statements into a foreach loop.
You get this error because you change the value of $selected inside the loop, but then check it outside the loop after it finishes:
You could make life easier on yourself by just applying the image inside your loop:
foreach($_POST['check'] as $selected){
echo $selected."</br>";
echo "<IMG SRC=\"{$selected}.jpg\">";
}
Here is a working sample: https://eval.in/437716
I'm supposed to make 1 PHP file called "access.php" that contains 11 pages. I have to do this with 1 PHP file. I'm supposed to accomplish this using functions to display each page. The "welcome" page allows a user to select "Administrator" or "User" via radio button. After hitting submit, the corresponding page should appear. Right now the admin/user page functions simply echo "Administrator Page" or "User Page" for testing purposes.
Ideally, a new page should appear that displays one of those centered at the top of the screen. But what's happening right now is the text "Administrator Page/User Page" just appears at the bottom of the welcome screen.
Here is my code:
<?php
#---Functions---
#**PHP Header**
#function phpHeader(){
#print <<< EOF
#<!DOCTYPE html>
#<head>
#</head>
# <body>
#EOF
#}
#**PHP Footer**
#function phpFooter() {
#echo "</body> </html>";
#}
#**Admin Page**
function adminPage(){
#phpHeader();
echo "<center><h1>Administrator Page</h1></center>";
#phpFooter();
}
#**User Page**
function userPage(){
#phpHeader();
echo "<center><h1>User Page</h1></center>";
#phpFooter();
}
#**Welcome Page**
function welcomePage(){
#phpHeader();
echo "<center><h1>Welcome</h1>";
echo "<br><br><br>";
echo "<h3> Select Login Type</h3>";
echo "<br><br><br>";
echo '<form name="access" action="" method="post">';
echo '<input type="radio" name="AccessLevel" value="admin" />Administrator <br />';
echo '<input type="radio" name="AccessLevel" value="user" /> User <br /><br />';
echo '<input type="submit" name="submit" value="Choose Level" />';
echo '</form></center>';
$AccessLevel = $_POST['AccessLevel'];
if (isset($_POST['submit'])) {
if (! isset($AccessLevel)) {
echo '<h2>Select an option </h2>';
}
elseif ($AccessLevel == "admin") {
adminPage();
}
else {
userPage();
}
}
#phpFooter();
}
welcomePage();
?>
Move this entire block at the top of your page, right under your opening <?php tag.
Sidenote: You can use return; or exit; or die();, the choice is yours; I used return;
$AccessLevel = $_POST['AccessLevel'];
if (isset($_POST['submit'])) {
if (! isset($AccessLevel)) {
echo '<h2>Select an option </h2>';
}
elseif ($AccessLevel == "admin") {
echo adminPage();
return;
}
else {
userPage();
return;
}
}
Which will echo only "Administrator Page" or "User Page" at the top of the page and nothing else.
<?php
function adminPage(){
return "<center><h1>Administrator Page</h1></center>";
}
function userPage(){
return "<center><h1>User Page</h1></center>";
}
function welcomePage(){
return '<center><h1>Welcome</h1>
<br><br><br>
<h3> Select Login Type</h3>
<br><br><br>
<form name="access" action="" method="post">
<input type="radio" name="AccessLevel" value="admin" />Administrator <br />
<input type="radio" name="AccessLevel" value="user" /> User <br /><br />
<input type="submit" name="submit" value="Choose Level" />
</form></center>';
}
$AccessLevel = $_POST['AccessLevel'];
if(isset($_POST['submit'])){
if(!isset($AccessLevel)){
echo welcomePage();
}elseif($AccessLevel=="admin"){
echo adminPage();
echo welcomePage(); // if you want to repeat that content at the bottom again
}elseif($AccessLevel=="user"){
echo userPage();
echo welcomePage(); // if you want to repeat that content at the bottom again
}
}else{//no form submitted
echo welcomePage();
}
?>
I have a form created by a while loop in php like this :
<form action='#' method='post'>
<input type='hidden' name='form_valid' id='form_valid'>
<?php
$i=-1;
$result_array = array();
//the while is from a simple mysql query
while( $line = $results->fetch() )
{
$i++;
echo"<input type='checkbox' class='checkbox' value='".$line->nid."' id='".$i."'>";
echo $line->title;
echo'<br>';
$result_array[$i] = $line->nid;
}
<input type='submit'>
?>
</form>
Then later on the code I'd like to store the values of the checked checkboxes only in a new array :
if (isset($_REQUEST['form_valid'])) //checking is form is submitted
{
foreach($result_array as $result)
{
if($result == $_REQUEST[$j]) <<<< ERROR
{
$final_array[$j] = $result;
}
}
}
Surprisingly, this code does not work at all.
The error message is "Notice : Undefined offset: 0", then offset 1 then 2 etc ...
The line where the message says theres an error is the marked one.
I really have no idea how to do this. Someone ? =)
Don't try to do it this way, this just makes it hard to process, just use a grouping name array: name="checkboxes[<?php echo $i; ?>]", then on the submission, all values that are checked should simply go to $_POST['checkboxes']. Here's the idea:
<!-- form -->
<form action="" method="POST">
<?php while($line = $results->fetch()): ?>
<input type="checkbox" class="checkbox" name="nid[<?php echo $line->nid; ?>]" value="<?php echo $line->nid; ?>" /><?php echo $line->title; ?><br/>
<?php endwhile; ?>
<input type="submit" name="submit" />
PHP that will process the form:
if(isset($_POST['submit'], $_POST['nid'])) {
$ids = $_POST['nid']; // all the selected ids are in here
// the rest of stuff that you want to do with it
}
It was working until I tried adding this statement
<?php echo "<input type=\"hidden\" name=\"hidden1\" value=\"$id\">" ?>
I was able to get the indexnum from my form before but when I added that line nothing seems to load in the fields.
Here is the full form:
<form name="approveform" method="POST" action="">
<?php echo "<input type=\"hidden\" name=\"hidden1\" value=\"$id\">" ?>
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
Its getting late and I probably need to just go to sleep but IM SO CLOSE!!! Here is the full code that processes the POST.
if($user_data['permissions'] >= 1)
{
// If users permission is 1 or 2 they get a field for inputting the index # and a button to change the approve field from 0 to 1 may need to make a new field to record who approved it....
//Determine if the order is already approved. If not approved show index field and allow user to approve it with index number
if($data2[0]['Approved'] == 1)
{
echo " <font color=\"green\"> Approved";
}
if($data2[0]['Approved'] == 0)
{
echo " Not Approved. Supply an index number and click approve to authorize this order to be completed.";
if (empty ($_POST) === false)
{
$required_fields = array('IndexNum');
foreach ($_POST as $key=>$value)
{
if (empty($value) && in_array($key, $required_fields) === true)
{
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
if (isset($_POST['success']) === true && empty($_POST['success']) === true)
{
echo 'Index has been updated and Order is now set to Approved';
}
else
{
if (empty($errors) === true)
{
$indexnum=$_POST['IndexNum'];
$approvedby=$user_data['lname'];
$vendorid1= $_POST['hidden1'];
echo $indexnum;
echo $approvedby;
echo $vendorid1;
//update_approved($indexnum, $approvedby, $vendorid1);
//header('Location: index.php');
//exit();
}
else if(empty($errors) === false)
{
echo output_errors($errors);
}
}
}
?>
<form name="approveform" method="POST" action="">
<?php echo "<input type=\"hidden\" name=\"hidden1\" value=\"$id\">" ?>
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
<?php }
}
Thank you all for looking into this. I get that $id value from a previous POST. I use it elsewhere in the code without issue.
Thank you all so much!
Try like
<input type="hidden" name="hidden1" value="<?php echo $id;?>">
Also try like
<?php echo '<input type="hidden" name="hidden1" value=".$id.">' ?>