I was trying to make a COMPUTERIZED ORDERING SYSTEM. My problem is how can I compute the 1st value on my checkbox. The second value on the checkbox will be posted on the summary of orders.
Once I've check all those three, it will compute the total amount of the menu and to display the selected menu on the summary of orders. But I can't figure out how can I display the total amount.
Can anybody guide me how to compute the total on my 1st value on the checkbox?
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" name="go" value= "Total">
</form>
<?php
//tosilog
$ts = $_POST['ts'];
$value = explode("|",$ts[0]);
echo $value[0];
echo $value[1];
//chiksilog
$cs = $_POST['cs'];
$value = explode("|",$cs[0]);
echo $value[0];
echo $value[1];
//porksilog
$ps = $_POST['ps'];
$value = explode("|",$ps[0]);
echo $value[0];
echo $value[1];
?>
<!-- compute for the 1st value on checkbox -->
<?php
$ts=$_POST['ts[0]'];
$cs=$_POST['cs[0]'];
$ps=$_POST['ps[0]'];
?>
<?php $compute = $ts[0] + $cs[0] + $ps[0];?>
<?php echo "$compute " ; ?>
If you're getting an array of checkbox elements, and they are numeric, you can use array_sum(). Not sure I understand your suggested structure, but I'll give you a code sample here based on the existing form structure. Then I'll post another bit to try to make this simpler for you. Executive summary: You do not need all the variables that are created by this form structure.
<?php // RAY_temp_user193.php
error_reporting(E_ALL);
$total = 0;
$inputs = array();
$errors = array();
if (!empty($_POST))
{
if (!empty($_POST['ts']))
{
foreach ($_POST['ts'] as $ts)
{
$inputs[] = current(explode(' |', $ts));
}
}
else
{
$errors[] = 'Tosilog';
}
if (!empty($_POST['cs']))
{
foreach ($_POST['cs'] as $cs)
{
$inputs[] = current(explode(' |', $cs));
}
}
else
{
$errors[] = 'Chiksilog';
}
if (!empty($_POST['ps']))
{
foreach ($_POST['ps'] as $ps)
{
$inputs[] = current(explode(' |', $ps));
}
}
else
{
$errors[] = 'Porksilog';
}
// IF ERRORS
if (!empty($errors))
{
echo 'UNABLE TO PRINT COMPLETE TOTAL. MISSING: ' . implode(',', $errors);
}
$total = array_sum($inputs);
if ($total) echo "<br/>TOTAL: $total <br/>" . PHP_EOL;
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$form = <<<ENDFORM
<form method="post">
<input name='ts[]' type='checkbox' value='40 |Tosilog'/> Tosilog
<br>
<input name='cs[]' type='checkbox' value='40 |Chiksilog'/>Chiksilog
<br>
<input name='ps[]' type='checkbox' value='45 |Porksilog'/>Porksilog
<br>
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;
See http://www.laprbass.com/RAY_temp_miggy.php
This is probably more along the lines of the way I would do it. The script knows what goes into the HTML and it knows exactly what to expect in the POST request. It is easy to add or remove different inputs. Often these kinds of inputs come from a data base table.
<?php // RAY_temp_miggy.php
error_reporting(E_ALL);
$total = 0;
// EXPECTED INPUTS
$inputs = array
( 'Tosilog' => 40
, 'Chiksilog' => 40
, 'Porksilog' => 45
)
;
if (!empty($_POST))
{
// ACTIVATE THIS TO SEE WHAT WAS SUBMITTED
// var_dump($_POST);
// SUM OF THE ELEMENTS
$total = array_sum($_POST);
echo "TOTAL: $total";
// SUM OF THE EXPECTED INPUTS
$expect = array_sum($inputs);
if ($total != $expect) echo " BUT THERE MAY BE INCOMPLETE INPUTS!";
// END OF THE ACTION SCRIPT
}
// CREATE THE FORM
$checkboxes = NULL;
foreach ($inputs as $name => $value)
{
$checkboxes
.= '<input name="'
. $name
. '" type="checkbox" value="'
. $value
. '" />'
. $name
. '<br/>'
. PHP_EOL
;
}
$form = <<<ENDFORM
<form method="post">
$checkboxes
<input type="submit" value= "Total">
</form>
ENDFORM;
echo $form;
Related
I had originally had the form inside of the foreach(ran into issues that seemed unsolvable because it would call the function as many times as the foreach had listed).
So now, with the <form> outside of the foreach it will only submit the data from the final collection in the foreach loop. But what I need it to do is send the data depending on which item in the foreach loop is checked.
This is my function for submitting the information to the database:
function user_add_new() {
global $wpdb;
$bookTOadd = $_POST["book"];
$listTOadd = $_POST["listID"];
$userID = $_POST["user"];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
And this is my foreach loop with the form outside of it:
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
?>
<?php if($r == ''.$current_user->ID.''|| $r == 'administrator') { ?>
<div class="user-wrap">
<div class="inner-wrap">
<!---entire checkbox--->
<div><span class="check">
<input type="checkbox" value="" onChange="this.form.submit()">
<input type="hidden" name="item" value="<?php echo $t;?>">
<input type="hidden" name="listID" value="<?php echo $o;?>">
<input type="hidden" name="userID" value="<?php echo $current_id;?>">
</span></div>
<!---entire checkbox--->
<!---info from book--->
<div>
<b><?php echo $s; ?></b><br>
<?php echo $d; ?>
</div>
<!---info from book--->
</div>
</div>
<?php } else {
}; ?>
<?php
};
?>
</form>
I did check the output with var_export($_POST); and it indeed does only return the data for the final item in the foreach loop when it needs to return data depending on which foreach item is checked
I have been stuck on this single form for hours now, I think I need a fresh mind to help find the solution. I truly appreciate any help!
Try this as your form:
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
I've removed the many <?php ?> statements and echoed the HTML in PHP. Also notice checkbox input has name='checkbox[]' value = '$index'.
The [] after the name means the values of the checked checkboxes will come through as an array in $_POST["checkbox"]. Since you are immediately submitting the form as soon as one is checked, you should only have one value in this array so we access that in the user_add_new() function with $_POST["checkbox"][0]
Then this is the function:
function user_add_new() {
global $wpdb;
$value = $_POST["checkbox"][0];
$bookTOadd = $_POST["item" . $value];
$listTOadd = $_POST["listID" . $value];
$userID = $_POST["userID" . $value];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
You had $bookTOadd = $_POST["book"]; but I couldn't see an input with book as a name so I assume this should be item?
I was trying to display the results of this form where when you checkbox a fruit, it shows that fruit, then on the last one it puts a "." period instead of a comma.
It comes down to something in my foreach loop that is causing this.
<span style="font-family: arial,helvetica,sans-serif; font-size: 12px;"><?php
$fruitArray = array('orange', 'apple', 'grapefruit', 'banana', 'watermelon');
if(isset( $_POST['fruit']))
{ $values = array();
$i = 0;
$length = count($_POST['fruit']);
echo 'Checkbox checked: ';
foreach ($_POST['fruit'] as $selection) {
if ($i == 0) {
//first to show
echo $selection . ' , ';
} else if ($i == $length - 1) {
//last to show
echo $selection . '.';
}else{
echo $selection . ' , ';
$i++;
}
}
}
I also was trying this:
foreach ($_POST['fruit'] as $selection) {
echo reset($selection) . " , ";
echo current($selection) . " , ";
echo end($selection) . " . ";
}
?>
<html>
<head>
<title>Checkbox selection using PHP (using PDO) and MySQL v2</title>
</head>
<body>
<h2>Pick your most favourite fruits:</h2>
<form name="fruitcheckbox" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="checkbox" name="fruit[]" value="orange"> Orange
<input type="checkbox" name="fruit[]" value="apple"> Apple
<input type="checkbox" name="fruit[]" value="grapefruit"> Grapefruit
<input type="checkbox" name="fruit[]" value="banana"> Banana
<input type="checkbox" name="fruit[]" value="watermelon"> Watermelon
<br>
<input type="submit" value="Save" name="btn_save">
</form>
</body>
</html> </span>
I added in here also if you only have 1 row, this is what you put in here:
$i = 0;
$length = count($_POST['fruit']);
//if one row
if ($length == '1'){
foreach ($_POST['fruit'] as $selection) {
echo 'Checkbox checked: '. $selection . '.';
echo 'Rows counted ' . $length;
}
}else{
echo 'Checkbox checked: ';
foreach ($_POST['fruit'] as $selection) {
echo $selection; //current fruit
if (each($_POST['fruit'])){
echo ", "; //current rows put a comma after fruit
}else if (!each($_POST['fruit'])) {
echo ".";//last row put period instead of comma
}
}
echo 'Rows counted ' . $length;
}
So I have the following code.
My main.html form lets me enter a value (a price for pc) and when I submit it calls the pcs.php script which displays all my pcs under the given value/price.
But I want to have an checkbox beside the information displayed by the script. ie
<br>alienware, 3000, gtx760 checkbox <br> asus rog, 2500, radeodhdxxxx checkbox <br>
and so on).
//main.html
<BODY>
<FORM METHOD="POST" ACTION="pcs.php" >
<INPUT TYPE='textbox' NAME='mypc' VALUE='' >
<INPUT TYPE="SUBMIT" NAME="Button" VALUE="Hit me">
</FORM> </BODY> </HTML>
//pcs.php
<?php
$dd = $_POST['mypc'];
$filename = "computer.txt";
$filepointer = fopen($filename,"r");
$myarray = file ($filename);
for ($mycount = 0; $mycount < count($myarray); $mycount++ )
{
$apc = $myarray[$mycount];
$price = getvalue($apc,1);
$part = explode(',', $apc);
//print $price ."<br>";
//print $str ."<br>";
if ($str <$dd )
{
for($pcount = 0; $pcount<3; $pcount++) {
print $part[$pcount] ."<br>";
}
print "<br>";
}
}
function getvalue ($text, $commaToLookFor)
{
$intoarray = explode(",",$text);
return $intoarray[ $commaToLookFor];
}
// fclose ($filepointer);
?>
<p>
</body>
</html>
// computer.txt file
alienware, 3000, gtx760<br>
asus rog, 2500, radeonhdxxx<br>
alienware, 5000, gtx titan<br>
In pcs.php you'll just need to modify your for loop to look something like:
// Create form
print '<form method="post" action="script_to_post_to.php">';
for ($mycount = 0; $mycount < count($myarray); $mycount++) {
$apc = $myarray[$mycount];
$price = getvalue($apc,1);
$part = explode(',', $apc);
if ($str < $dd) {
for($pcount = 0; $pcount<3; $pcount++) {
print $part[$pcount] ."<br>";
}
// Add checkbox and name with product type
print '<input type="checkbox" name="' . getvalue($apc, 2) . '" />';
print "<br>";
}
}
// Provide form submission button and close form element
print '<input type="submit" value="Submit" />';
print '</form>';
You'll have a form with each element having a checkbox and the ability to respond to the list of checked items in "script_to_post_to.php".
i have a website where the admin can choose to add a certain number of bbcode tags and the corresponding html tags.
First he chooses how many tags he wants to add from a drop down select form in a for Each loop.
Depending on how many tags he chose when he clicked the submit button, the corresponding number of input tags appear in a second form, also in a for Each loop. He fills in the bbcode and html input and clicks the submit button. Normally the tags should be added to my database but in this case when he clicks submit the form disappears and nothing is added..
Here is the code :
//FIRST FORM WHERE HE DECIDES HOW MANY TAGS TO ADD
<form id='nbbalises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>How many tags ?</legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
echo '<select name="number">';
$range = range(1,50,1);
foreach ($range as $nb) {
echo "<option value='$nb'>$nb</option>";
}
echo "</select>";
?>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form><br /> <br />
<?php
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
//SECOND FORM WHERE I GENERATE THE INPUT DEPENDING ON THE NUMBER CHOSEN FROM FIRST FORM
<form id='balises' action='config.ini.php' method='post' accept-charset='UTF-8'>
<fieldset>
<legend>Balises bbc : </legend>
<input type='hidden' name='submitted' id='submitted' value='1' />
<?php
foreach ($range2 as $nb2) {
echo "<label>bbcode tag $nb2 :</label>
<input type='text' size='40' name='bbc$nb2' id='bbc$nb2' maxlength='40' />
<label>html tag $nb2 :</label>
<input type='text' size='40' name='html$nb2' id='html$nb2' maxlength='40' />
<br />";
}
}
?>
<input type='submit' name='Submit2' value='Submit2' />
</fieldset>
</form>
<?php
//PROBLEM STARTS HERE, NOTHING WORKS UNDER HERE
if (isset($_POST['Submit2'])){
//CONNECT TO MY DATABASE
connectDB();
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
}
mysql_close();
}
}
//MY FUNCTIONS TO ADD THE BBCODE AND HTML TO DATABASE
function connectDB(){
//connexion DB
$link = mysql_connect('127.0.0.1', 'USERNAME', 'PASSWORD');
if (!$link) {
die('Erreur de connexion: ' . mysql_error());
}
$db = mysql_select_db('1213he200967',$link) or die("N'a pu selectionner
1213he200967");
mysql_query("SET NAMES 'utf8'");
}
function addBbc($bbc, $html){
$b = mysql_real_escape_string($bbc);
$h = mysql_real_escape_string($html);
$query="INSERT INTO bbcode (BBC,HTML) VALUES ('$b','$h')";
$result = mysql_query($query) or die("error");
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
return false;
}
else return true;
}
Thank you very much, and sorry if my code is amateur-ish, i'm only starting in php.
EDIT
Found part of my problem
$number = $_POST['number'];
$range2 = range(1,$number,1);
This goes from 1 to the number chosen by the user in the first form.
for ($i=0; $i<$number ; $i++){
if (!(empty($_POST["bbc$i"])) && (empty($_POST["html$i"])))
//FUNCTION ADDS TAGS TO DATABASE
addBbc($_POST["bbc$i"], $_POST["html$i"]);
This goes from 0 to $number - 1
So i changed my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
if (!(empty($_POST["bbc$nb"])) && (empty($_POST["html$nb"]))) {
addBbc($_POST["bbc$nb"], $_POST["html$nb"]);
}
else echo "$nb tags empty ";
This works a bit better but now it goes to the else just here above and displays "2 tags empty", so it still doesn't quite work.
Ok to solve it I finally decided to post the data from the second form to another page and i modified my code to this.
for ($i=0; $i<$number ; $i++){
$nb = $i + 1;
$varBbc = 'bbc'.$nb;
$varHtml = 'html'.$nb;
if ((isset($_POST[$varBbc])) && (isset($_POST[$varHtml]))) {
addBbc($varBbc, $varHtml);
}
else echo "$nb tags empty ";
}
Apparently using !empty instead of isset doesn't work in this case, maybe because of the html tags.
$nb should be in double quotes.
so echo "<option value='$nb'>$nb</option>"
change to echo "<option value='".$nb."'>$nb</option>";
and also
if (!(empty($_POST['number']))) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
change to:
if (isset($_POST['submit'])) {
if ($_POST['number'] >= 1 && $_POST['number']<= 50){
$number = $_POST['number'];
$range2 = range(1,$number,1);
?>
I have html form that looks like:
<form method="post" action="?a=up">
...some mysql query...
while ($i = mysql_fetch_array($result)) {
<input name="name[]" type="text" value="<?=$i['name'];?>" />
<input name="years[]" type="text" value="<?=abs($age);?>"/>
<input name="to[]" type="checkbox" value="<?=$i['id'];?>" />
}
<input name="" type="submit" value="go" />
</form>
The problem I have is that I can not get the values of the form fields such as "name" and "years".
I can only get a list of the ids (value of "to" checkbox).
The php code looks like:
$cnt = 0;
for($p = 0; $p <= (sizeof($to)-1); $p++)
{
echo $to[$p].$name[$p].$years[$p]"<br>";
$cnt++;
}
$tm = array($cnt);
What I'm doing wrong?
You're expecting a checkbox to be a successful control even if it isn't checked (and the specification says that it must not be so).
You should probably do something along the lines of:
<input name="name[<?php echo htmlspecialchars($i['id']); ?>]"
value="<?php echo htmlspecialchars($i['name']); ?>" />
<input name="years[<?php echo htmlspecialchars($i['id']); ?>]"
value="<?php echo abs($age);?>"/>
Update
Here is how you can get checkboxes that are checked using isset:
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$cnt = 0;
for($p = 0; $p <= (sizeof($_POST['to'])-1); $p++)
{
if (isset($_POST['to'][$p]))
{
echo $_POST['to'][$p] . $_POST['name'][$p] . $_POST['years'][$p] . "<br>";
$cnt++;
}
}
$tm = array($cnt);
}
You are not getting the fields from POST array, here is how your code should be:
$cnt = 0;
for($p = 0; $p <= (sizeof($_POST['to'])-1); $p++)
{
echo $_POST['to'][$p] . $_POST['name'][$p] . $_POST['years'][$p] . "<br>";
$cnt++;
}
$tm = array($cnt);
Make sure that above code executes when form is submitted by putting it in this condition:
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$cnt = 0;
for($p = 0; $p <= (sizeof($_POST['to'])-1); $p++)
{
echo $_POST['to'][$p] . $_POST['name'][$p] . $_POST['years'][$p] . "<br>";
$cnt++;
}
$tm = array($cnt);
}
And finally a little suggestion that you should avoid using short php tags <?=?> for they have posed security issues and can easily be embedded into images or xml. (Make sure that they are also turned on from php.ini if you want to use them)
Why dont you just try
$cnt = 0;
foreach ( $_POST['to'] as $k => $to ){
echo $_POST['to'][$k] . $_POST['name'][$k] . $_POST['years'][$k] . "<br />";
$cnt ++;
}
$tm = array ($cnt);