Im trying to add a class after a form is submitted depending on the option the user chose.
<form enctype="multipart/form-data" action="upload.php" method="POST">
title:<br />
<input type="text" name="title" value="" /> <br />
description:<br />
<input type="text" name="description" value="" /> <br />
Categories:<br />
<input type="checkbox" name="categories[]" value="1">Landscpae<br />
<input type="checkbox" name="categories[]" value="2">Portrait<br />
<input type="checkbox" name="categories[]" value="3">Monochrome<br />
Please choose an image: <input name="uploaded" type="file" /><br />
<input type="submit" value="Upload" />
</form>
<li class='INSERT OPTION HERE'> test </li>
With the option to select more than one class so add a space after each one.
on my database the Value="1" "2" "3" == the option name
let me know if more information is needed
Something along these lines might work:
$valid = array(1,2,3);#valid items
if(isset($_POST['categories']) && is_array($_POST['categories'])){
$post = array_unique($_POST['categories']);#you might not need this, but this removes duplicate values
foreach($post as $key => $value){
if(in_array($value, $valid)){
$class = true;
}else{
unset($post[$key]);#remove bad values, also this may not be necessary but removes unwanted items.
}
}
if(isset($class)){
$class = 'class="class' . implode(' class', $post) . '"';
}
}#else needed for non array categories?
<li <?php if(isset($class)){ echo $class;} ?> > test</li>
DEMO
You want to make sure that the form is submitted, and if it is then you echo a class and can create a switch statement that will alter the class depending on what was selected.
<li
<?php
if(isset($_POST['categories'])) {
echo 'class="';
switch($_POST['categories']) {
case 1;
echo 'class1';
break;
case 2;
echo 'class2';
break;
case 3;
echo 'class3';
break;
echo '"';
}
}
?>
> test </li>
Related
I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;
.
The background
I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.
The div on the right of the page will then load a "basket" which will use these post values and add them to an array.
When the "add" button is used again the value should update to +1 rather than create another sub_array.
.
What is currently happening
Currently when I click "add" the first time it adds the array as expected;
However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.
On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity
It just seems to be that second time I click "add".
.
The Script
<?php session_start();
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}
if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}
Sample form
<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!
Many thanks to all in advance!
I tried to debug your code and a possible solution could be the following:
<?php
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
if (isset($_POST["prod"]))
{
$prod_id=$_POST["prod"];
//let suppose $_POST['prod'] is your item id
$found=false;
for($i=0;$i<count($_SESSION['cart']);$i++)
{
if(isset($_SESSION['cart'][$prod_id]))
{
echo "found! so add +1";
$_SESSION['cart'][$prod_id][2]+=1;
$found=true;
break;
}
}
if($found==false)
{
echo 'not found! so create a new item';
$_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Another way to do it is using associative arrays.
The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
an array with properties as name=>value for each item.
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
//let's suppose you have unique names for items
if (isset($_POST["prod"]))
{
$name=$_POST["name"];
if(isset($_SESSION['cart'][$name]))
{
echo "found! so add +1";
$_SESSION['cart'][$name]['quantity']+=1;
}
else
{
echo 'not found! so create a new item';
$_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] =[];
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-OMIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:
$_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);
For:
$_SESSION["cart"][0][2]+= 1;
By the way, try to properly indent your code when you are going to post it. It is hard to read.
I have a form built with checkboxes but I am unable to calculate the total result for it. I want to get the total if user selects three checkboxes total will be $3 if one then $1. I am stuck as I am unable to do the calculation.
<html
<head>
<title>Order</title>
</head>
<body>
<link rel= "stylesheet" href= "order.css">
<form action="complete.php" method="post">
<form name="order">
<fieldset><legend>Complete Order:</legend>
<h1> Choose Design </h1>
<p><label>Your Name: <input type="text" name="name"></label>
<label>Address: <input type="text" name="address"></label>
<label>Credit Card #: <input type="text" name="creditcard"></label>
<label>Date: <input type="date" id="datepicker" name='date' size='9' value="" > </label>
<br><label> Design Types: <img src="1.jpg"><input type="checkbox" name="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="2"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="3"> </label>$1.00
<br></p>
<input type="submit" value="Submit Order">
</form>
</body>
</html>
Php code
<html>
<head>
<title>Form Feedback</title>
</head>
<body>
<?php
if ( !empty($_POST['name']) && !empty($_POST['address']) && !empty($_POST['creditcard']) ) {
echo "<p>Thank you, <strong>{$_POST['name']}</strong>, for placing the order.
<p>Your item will be shipped to:
<tt>{$_POST['address']}</tt></p>
<p>Following credit card has been charged: <em>{$_POST['creditcard']}</em>.</p>\n";
} else { //Missing form value.
echo '<p>Please go back and fill out the form again.</p>';
}
?>
</body>
</html>
Changes in HTML:
<label><img src="1.jpg"><input type="checkbox" name="fieldname[]" value="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="fieldname[]" value="1"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="fieldname[]" value="1"> </label>$1.00
PHP Code: it will count number of selected checkboxes-
<?php
if(isset($_POST['fieldname']) && !empty($_POST['fieldname'])){
echo count($_POST['fieldname']); //count the number of selected checkbox
echo array_sum($_POST['fieldname']); //sum of selected checkbox values
}
?>
Use isset($_POST['checkboxName']) to check if the checkbox is checked and then add 1 for each checkbox:
$check_value = 0;
$check_value += isset($_POST['1']) ? 1 : 0;
$check_value += isset($_POST['2']) ? 1 : 0;
$check_value += isset($_POST['3']) ? 1 : 0;
Change the php part:
<?php
if ( !empty($_POST['name']) && !empty($_POST['address']) && !empty($_POST['creditcard']) ) {
$cost = 0;
if(isset($_POST['1'])) $cost += 1;
if(isset($_POST['2'])) $cost += 1;
if(isset($_POST['3'])) $cost += 1;
echo "<p>Thank you, <strong>{$_POST['name']}</strong>, for placing the order.
<p>Your item will be shipped to:
<tt>{$_POST['address']}</tt></p>
<p>Following credit card has been charged: <em>{$_POST['creditcard']}</em>.</p>
<p>With amount: <em>{$cost}</em>.</p>\n";
} else { //Missing form value.
echo '<p>Please go back and fill out the form again.</p>';
}
?>
First of all, it's about checkbox's name. If they are a group of values (e.g: products), use a common name as an array:
<input type="checkbox" name="product[]" />
<input type="checkbox" name="product[]" />
<input type="checkbox" name="product[]" />
The second question, shouldn't your checkbox has a value or it'll be always $
1.00?
It it'll be always $1.00, just count it:
$value = isset($_POST['product']) ? count($_POST['product']) : 0;
If it should has a value:
<input type="checkbox" name="product[]" value="1.00" />
<input type="checkbox" name="product[]" value="1.50" />
<input type="checkbox" name="product[]" value="2.00" />
Can use the array_sum function:
$value = isset($_POST['product']) ? array_sum($_POST['product']) : 0;
Im trying to save $_SESSION data to keep checked values on page refresh, I have some code written up but I am missing a piece.
Session Code:
session_start();
if(isset($_POST['submit'])) {
//user posted variable
$checks = $_POST['personalization_result'];
if(isset($_POST['personalization_result'])) {
$_SESSION['value'] = $_POST['personalization_result']; }
else {
$_SESSION['value'] = '';
}
}
Form Code:
<form action="" method="post" id="question-form">
<input type="hidden" name="submit" value="1">
<li>
<input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_SESSION['value']['memory_0'] ?>" value="0" />
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" />
</li>
<li>
<input name="personalization_result[memory_1]" type="hidden" class="<?php echo $_SESSION['value']['memory_1'] ?>" value="0" />
<input name="personalization_result[memory_1]" type="checkbox" value="1" id="personalization_result_memory_1" />
</li>
//There are many checkboxes, this is just two for demo purposes
<input class="submit" type="submit" value="Send" />
</form>
For testing I am echoing $_SESSION['value']['memory_0'] && $_SESSION['value']['memory_1']inside the hidden input, they return properly, if the input is checked the class is 1, if it's unchecked the class is 0.
I am not sure the best way to say if it = 1 then echo checked="checked"
My shotty attempt:
<input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_SESSION['value']['memory_0'] ?>" value="0" />
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" <?php if($_SESSION['value']['memory_0'] = 1) {echo 'checked="checked"';} ?> />
This returns an error "Cannot use a scalar value as an array", that and I dont like how thats written up.
So with all the given information, whats the best way to write if my value = 1 return checked="checked"?
This will make your PHP much cleaner and scalable:
Use this function at the top:
session_start();
function checkbox($id)
{
$isChecked = '';
if (isset($_SESSION['value']['memory_'.$id]))
{
$isChecked = ($_SESSION['value']["memory_".$id] == 1) ? 'checked="checked"' : '';
}
echo '<input name="personalization_result[memory_'.$id.']" type="checkbox" ';
echo 'value="1" id="personalization_result_memory_'.$id.'" ';
echo $isChecked.' />';
}
and then instead of writing out <input ... <?php ... ?> ... /> for every single checkbox, just use
<?php checkbox(0); ?>
<?php checkbox(1); ?>
Your short attempt has an error:
instead of <?php if($_SESSION['value']['memory_0'] = 1) try <?php if($_SESSION['value']['memory_0'] == 1)
i tried alot in order to fetch values from database and put it in check-box array but failed.Please help!!
*img[] comes out to be empty all the time like no value is going into it when ever i call that part using $_POST(['img'])!!*
here's my code:
echo " <h2>Select image to delete: <h2>";
$s = mysql_query("SELECT * FROM image WHERE u_id = '$u_id'");
$num = mysql_num_rows($s);
if($s)
{
?>
<form name="f1" method="post" action="">
<?php
while($row = mysql_fetch_array($s))
{
?>
<input type="checkbox" name="img[]" value="<?php $row['path'] ;?>" />
<img width="100" src="<?php echo $row['path']." ";?>">
<?php
}
?>
<br />
<br />
<input type="submit" name= "subDel" value = "Delete" />
</form>
<?php
}
What about this? :)
<input type="checkbox" name="img[]" value="<?php $row['path'] ;?>" />
=>
<input type="checkbox" name="img[]" value="<?php ECHO $row['path'] ;?>" />
Retrive post Data in PHP by using $_POST['variableName'] - no brackets, case DOES matter
In your case, $_POST['img'] is of type array. There is NO value for unchecked items. If nothing checked, your post variable is empty or even undefined (didn't test it yet).
Access your values by
if (array_key_exists($index, $_POST['img']) == true) {
// $index is checked
$doSomething = $_POST['img'][$index];
}
I'm a complete newbee in php (started just last week)
Issue is like this:
Basically, I was trying to ensure that once a sub-form is filled, then it is not altered. So, I used !isset to display the sub-form (i.e. if !isset is true) and if !isset is false, then it hides that sub-form and shows the next sub-form (the individuals form has only been designed).
<?php include($_SERVER['DOCUMENT_ROOT'].'/officespace/includes/functions.php');
echo'<html>
<head>
<title> Create </title>
</head>
<body>';
if(!isset($_POST["Category"])){
/* if no category is selected, then this code will display the form to select the category*/
Echo "Pls Select Category before clicking on Submit Category";
/* Breaking out of PHP here, to make the form sticky by using a php code inside form action*/
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Select the Category of Person: </legend><br />
<input type="radio" name="Category" value="Individual" /> Individual<br /><br />
<input type="radio" name="Category" value="Company, Pvt Ltd" /> Company, Pvt Ltd<br /><br />
<input type="radio" name="Category" value="Company, Ltd" /> Company, Ltd<br /><br />
<input type="radio" name="Category" value="Partnership Firm" /> Partnership Firm<br /><br />
<input type="radio" name="Category" value="LLP Firm" /> LLP Firm<br /><br />
<input type="radio" name="Category" value="HUF" /> HUF<br /><br />
<input type="submit" name='Submit Category' value="Submit Category" /><br />
</fieldset>
</form>
<?php
} Else {
$Category = $_POST["Category"];
Echo "$Category";
Echo "<br />";
/* Using swich statement to test the value of Category, and accordingly echo appropriate forms*/
switch ($Category) {
case "Individual":
if(!isset($_POST['Submit_Data_for_Individual'])){
//if no data for individual is submitted,
//then this code will display the form to enter and submit data for Individual
Echo /*displays message*/
"Pls Enter the Data for the Individual";
?>
<form action="<?php Echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<br />
First Namee: <input type="text" name="Individual_First_Name" />
<br />
Middle Name: <input type="text" name="Individual_Middle_Name" />
<br />
Last Name: <input type="text" name="Individual_Last_Name" />
<br />
Date of Birth: <input type="text" name="date_of_birth/incorporation" />
<br />
Gender:
<br />
<input type="radio" name="Gender" value="male" /> Male
<br />
<input type="radio" name="Gender" value="female" /> Female
<br />
Email 1: <input type="text" name="email_1" />
<br />
<input type="submit" name="Submit_Data_for_Individual" value="Submit Data for Individual" />
</fieldset>
</form>
<?php
}Else
{
$email_1 = $_POST["email_1"];
$Gender = $_POST["Gender"];
validate_email($email_1); // this is a custom function which i made
Echo $Gender; // just to see if value has been passes. problem lies here because its not showing anything
// run other validations here
// and if all valid then run mysqli insert query for individuals record
}
break;
case "Company, Pvt Ltd":
echo "Company, Pvt Ltd";
break;
case "Company, Ltd":
echo "Company, Ltd";
break;
case "Company, Ltd":
echo "Company, Ltd";
break;
case "Partnership Firm":
echo "Partnership Firm";
break;
case "LLP Firm":
echo "LLP Firm";
break;
case "HUF":
echo "HUF";
break;
case NULL:
echo "Error: nothing selected";
break;
}
}
echo '</body>
</html>';
?>
Is see one problem immediately.
You are checking for a form input called Submit Data for Individual, but that is the value of a submit button which has no name attribute. Set a name='submit-data' attribute on the submit button and change the conditional to check for the name instead of its value:
// This will never match.
if(!isset($_POST["Submit Data for Individual"])){
// Change it to
if(!isset($_POST["submit-data"])){
// Then change this
<input type="submit" value="Submit Data for Individual" />
// To this:
<input type="submit" name='submit-data' value="Submit Data for Individual" />
Additionally, the default case in a switch statement uses a default keyword:
// You may safely change this:
case NULL:
echo "Error: nothing selected";
break;
// To this:
default:
echo "Error: nothing selected";
break;
Addendum:
The following code is never reachable, since the form posts to another script, create.php. If you change the <form> action attribute to post back to <?php $_SERVER['PHP_SELF'];?> instead of to create.php, you should see the else case. Right now, it doesn't work because your if tests that $_POST["submit-data"] is set. It can only be set if the form has been submitted, but the form submits to an external script.
// This else case can never be reached...
}Else
{
validate_email($_POST["email_1"]); // this is a custom function which i made
Echo $_POST["Gender"]; // just to see if value has been passes. problem lies here because its not showing anything
// run other validations here
// and if all valid then run mysqli insert query for individuals record
}
To fix this and see your Gender echoed out, temporarily change
<form action="create.php" method="post">
// change to
<form action="' . $_SERVER['PHP_SELF'] . '" method="post">
Addendum 2
You are checking if Category is set, but after posting the user form, it will not be:
// Change
if(!isset($_POST["Category"])){
// To check that the user form was not submitted
if (!isset($_POST["Category"]) && !isset($_POST['submit-data'])) {
Then you need to test if the user form was submitted. Before the Else { $Category = $_POST['Category']; section, add an else if to process the user form.
if (!isset($_POST["Category"]) && !isset($_POST['submit-data'])) {
// Show the Category form...
}
// Process the user form...
else if (isset($_POST['submit-data'])) {
validate_email($_POST["email_1"]); // this is a custom function which i made
Echo $_POST["Gender"];
}
// Now process the categories or show the user form...
else {
$Category = $_POST['Category'];
// etc...
}
Finally, remove the whole Else block from your individual case, as it cannot be used there.