Checking all $_POST values for answer and printing - php

I am creating an online grocery site where a user can enter his/her full name & address and then proceed to purchase groceries.
There are 20 grocery items to choose from - if the user wants an item, they can simply enter how many units of that item they want; this is the html code for for just 1 of the 20 items.
<tr>
<td> Milk - $3.99/carton </td>
<td> <input type="number" name="amtMilk" min=0> </td>
</tr>
At the bottom of the page there is a submit button which leads to a confirmation page in php. The confirmation page outputs the users name, address, all the items ordered and a total before and after tax.
I have written out the PHP for this however, it doesn't seem to be working correctly. Below is my code shortened to 4 items:
<?php
<h2> Customer Details: </h2>
<p>Customer Name: </p> echo $_POST['Name'];
<p>Address: </p> echo $_POST['Address'];
$total = 0;
<p>You ordered: </p>
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
foreach($POSTvalues as $key) {
if ($_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
elseif ($_POST['amtEggs'] > 0 ) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
elseif ($_POST['amtBread'] > 0 ) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
elseif ($_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total"; <br>
$afterTax = $total*0.13 + $total
$afterDelivery = $afterTax + 3.50
echo "Your total after tax is: $afterTax"; <br>
echo "Your total after delivery is: $afterDelivery";<br>
<h3> GRAND TOTAL: </h3> echo "$afterDelivery";
?>
Can anyone point out what i'm doing wrong or how I can fix this so get the desired output?

There is no need for the foreach loop, and thus no need for the $POSTvalues array.
Use independent if statements without the elseif.
A little psuedocode...
if (value1 > 0 )
{
add to total
print item
}
if (value2 > 0 )
{
add to total
print item
}
if (value3 > 0 )
{
add to total
print item
}
if (value4 > 0 )
{
add to total
print item
}

Fun fact: PHP turns elements with names structured like arrays into PHP arrays.
So, you can do this:
<?php
$array = array(
"milk" => array(
"price" => 3.99,
"unit" => "carton",
),
"eggs" => array(
"price" => 2.99,
"unit" => "dozen",
),
);
if (isset($_POST['amt'])) {
var_dump($_POST['amt']);
$total = 0;
foreach ($_POST['amt'] as $name=>$num) {
if($num > 0) {
$price = $array[$name]['price'];
$amt = $_POST['amt'];
$total += $price * $num;
echo $num . " " . ucfirst($name) . ", ";
}
}
echo "<br />Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo '<form method="POST"><button type="submit">Back</button></form>';
} else {
?><form method="POST"><table><?php
foreach ($array as $name=>$item) {
?>
<tr>
<td> <?php echo ucfirst($name); ?> - $<?php echo $item['price']; ?>/<?php echo $item['unit']; ?> </td>
<td> <input type="number" name="amt[<?php echo $name; ?>]" min=0> </td>
</tr><?php
}
?></table><input type="submit"></form><?php
}
I would consider either passing your price as a hidden field (for example, with the name price[milk]), or ensuring your array is available after you've submitted the form like I have done above. That way you don't have to hard-code in prices. The way you have it, it's going to be a nightmare to change if the prices change!
To add a new item, all you need to do is add a new key/array pair to the $array. No additional coding on the back-end. Just results.
Check it out here.

you're doing many things wrong.
so, how are you trying to display html inside php without using print/echo?
So here's revised code, hope this will resolve your issues.
<?php
echo '<h2> Customer Details: </h2>';
echo '<p>Customer Name: </p>'. $_POST['Name'];
echo '<p>Address: </p>'. $_POST['Address'];
$total = 0;
echo '<p>You ordered: </p>';
$POSTvalues = array('amtMilk', 'amtEggs', 'amtBread', 'amtCereal');
//foreach($POSTvalues as $key)
{
if (isset($_POST['amtMilk']) && $_POST['amtMilk'] > 0) {
$total+= 3.99*($_POST['amtMilk']);
echo "Milk";
}
if (isset($_POST['amtEggs']) && $_POST['amtEggs'] > 0) {
$total+= 2.99*($_POST['amtEggs']);
echo "Eggs";
}
if (isset($_POST['amtBread']) && $_POST['amtBread'] > 0) {
$total+= 1.50*($_POST['amtBread']);
echo "Bread";
}
if (isset($_POST['amtCereal']) && $_POST['amtCereal'] > 0 ) {
$total+= 4.99*($_POST['amtCereal']);
echo "Cereal";
}
}
echo "Your total before Tax is: $total<br />";
$afterTax = $total*0.13 + $total;
$afterDelivery = $afterTax + 3.50;
echo "Your total after tax is: $afterTax<br />";
echo "Your total after delivery is: $afterDelivery<br />";
echo "<h3> GRAND TOTAL: </h3>$afterDelivery";
?>
EDIT
Comment out the foreach($POSTvalues as $key) and change all elseif to if.
add another condition in if statement like this && $_POST['amtCereal'] > 0 to ensure that it has value greater than 0

Related

php how to do a loop to calculate score for a quiz website

i am creating a quiz website using php where there are 4 questions for users to answer. there is a home page before this for them to choose either math or lit that they wish to do.
after selecting the subject, user need to answer the question and submit their answer, then the php code will calculate their score and count the number of correct/wrong answers.
<ArrayquesAns.php> is the array of questions and answers
it looks something like this, there are 2 array in this php, 1 is math question and another 1 is lit question
and here is the main code where it will generate questions from the question pool randomly. i also tried to put in the code to calculate score
<html>
<body>
<?php
require_once 'ArrayQuesAns.php'; //retrieve array of ques
$_SESSION["subject"] = $_GET['subject']; //suppose to put value when session starts
$_SESSION["name"] = $_GET['name'];
$subject = $_SESSION["subject"];
$name = $_SESSION["name"];
$url = "displayScore.php?name=" . $name . "&subject=" . $subject . "&";
if ($subject == "mathematics") { //math session
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
$MathquesRand = array(); //New array to contain the 4 random rows
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?> </h1>
<p>Hello <?= $name ?>! You may start your quiz !<p>
<hr>
<?php foreach ($MathquesRand as $qtsno => $value) { ?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
} else { //Lit Section
$LitQues_key = array_rand($Litques, 4);
$LitquesRand = array();
$i = 0;
foreach ($LitQues_key as $key) {
$LitquesRand[$i] = $Litques[$key];
$i++;
}
?>
<form action="<?= $url ?>" method="get">
<h1> Section : <?= $subject ?></h1>
<p>Hello <?= $name ?> ! You may start your quiz !<p>
<hr>
<?php foreach ($LitquesRand as $qtsno => $value) {
echo $value["ques"], " = \t";
?> <!--Display Question -->
<input type="text" name="userans" value="<?php echo isset($_GET["userans"]) ? $_GET["userans"] : ''; ?>">
<br>
<?php } ?>
<?php
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
?>
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
}
?>
<!--Exit-->
<button type="button">EXIT</button>
</body>
</html>
i think this part is where it has issue
foreach ($MathquesRand as $qtsno => $value) {
array_key_exists($userans = $_GET["userans"]);
$score = 0;
$overall = 0;
$correct = 0;
$wrong = 0;
if ($userans == $value["ans"]) {
$correct += 1;
} else {
$wrong += 1;
}
$score = ($correct * 5) - ($wrong * 3);
"\n\n\n";
echo $value["ans"];
echo $correct;
echo $wrong;
echo $score;
}
the code should match user input answer with array question/answer to see if the answer is correct. every correct question will *5 and every wrong answer will *3 (the formula is in the code).
i am not sure if i place the code in the wrong bracket hence its not working or there is some logic error or should i run the code to find the score in a separate php?
after user submit their answer, it will redirect to another page that display their score and number of correct/wrong answers like this
score display html
Based on your original version of the MC test, please find below a working version:
To make it simple, I have removed the "Name" and "Subject" of the form to demonstrate the necessary coding.
You can still use the array_rand to draw 4 random questions
However, after the questions are displayed to the student (and student can input the answer) and clicked "Submit Attempt", the page will remember the random questions drawn - I have used a trick :- to store the questions randomly drawn into a hidden input box
The system will compare the student's submitted answer with that of the correct answer and determine whether it is correct or wrong, and show the score
To fix the "undefined array" errors you encountered, I applied the isset function on places relating to the $_GET variables. (Actually these are warnings, not errors, but it is for sure a good practice to use isset)
<?php
//require_once 'ArrayQuesAns.php'; //retrieve array of ques
$Mathques=array(
1=> array('no'=>1, 'ques'=>"3+1", 'ans'=>"4"),
2=> array('no'=>2, 'ques'=>"3+3", 'ans'=>"6"),
3=> array('no'=>3, 'ques'=>"3+4", 'ans'=>"7"),
4=> array('no'=>4, 'ques'=>"3+5", 'ans'=>"8"),
5=> array('no'=>5, 'ques'=>"3+6", 'ans'=>"9"),
6=> array('no'=>6, 'ques'=>"3+7", 'ans'=>"10"),
7=> array('no'=>7, 'ques'=>"3+8", 'ans'=>"11"),
8=> array('no'=>8, 'ques'=>"3+9", 'ans'=>"12"),
9=> array('no'=>9, 'ques'=>"3+10", 'ans'=>"13"),
10=> array('no'=>10, 'ques'=>"3+11", 'ans'=>"14")
);
if (! isset($_GET["draw"])) {
$mathQues_key = array_rand($Mathques, 4); //Pick 4 random rows in array
}
$MathquesRand = array(); //New array to contain the 4 random rows
if (! isset($_GET["draw"]) ) {
$i = 0;
foreach ($mathQues_key as $key) {
$MathquesRand[$i] = $Mathques[$key];
$i++;
}
}
?>
<?php
if (isset($_GET["draw"]) && $_GET["draw"] !="") {
$pieces = explode(",", $_GET["draw"]);
$index=0;
while ($index < count($pieces)) {
if ($pieces[$index]!=""){
$MathquesRand[] = $Mathques[$pieces[$index]];
}
$index++;
}
}
?>
<form action="" method="get">
<?php
$correct=0;
$wrong=0;
?>
<h1> Section : Mathematics </h1>
<p>Hello ! You may start your quiz !<p>
<hr>
<?php
$pool="";
$ii=1;
foreach ($MathquesRand as $qtsno => $value) {
$pool.= $value["no"]. ",";
?>
<?php echo $value["ques"] . " = \t"; ?> <!--Display Question -->
<input type="text" name="userans<?php echo $ii; ?>"
<?php if (isset($_GET["userans".$ii]))
{
echo " value='" .$_GET["userans".$ii] . "'>" ;
} else { echo ">" ; }
?>
<?php if (isset($_GET["userans".$ii]) && $_GET["userans".$ii]==$value["ans"]) {
$correct++;
} else {
$wrong++;
}
?>
<br>
<?php
$ii++;
}
?>
<input name=draw type=hidden value="<?php echo $pool; ?>">
<br>
<button type="submit">SUBMIT ATTEMPT</button>
</form>
<?php
$score = ($correct * 5) - ($wrong * 3);
?>
<?php if (isset($_GET["draw"])) { ?>
<font color=red>Result:</font>
<br>Correct:<?php echo $correct;?>
<br>Wrong:<?php echo $wrong;?>
<br>Score:<?php echo $score;?>
<?php } ?>
To share my experience (I have coded such Multiple Choice Q & A functions many times) , in future if you want to do similar thing, please consider using
database to store the drawn questions ;
use ajax to compare the input data with the correct data stored in the db, instead of using form submission

get td values display as static in codeigniter

Hi guys i am trying to display the first td values as static so i have keep those values in one array and i try to increase the values and try to display but when i get it is displaying depending on foreach values if i have one record in foreach it is displaying one value and if i have 2 records it is displaying 2 values.
But i want to display all td value if i have values in foreach or not also.
Here is my code:
<tbody>
<?php
$arr = array(0=>'On Hold',1=>'Asset Incomplete',2=>'SME Discussion',3=>'a',4=>'b',5=>'c',6=>'d',7=>'e',8=>'f',9=>'g',10=>'h');
$i = 0;
foreach($getCourse as $report)
$status= $report->status;
{
?>
<tr>
<td><?php echo $arr[$i]; ?>
<?php $i++; ?></td>
<td><?php
if($status==1)
{
echo "On Hold";
}
elseif($status==2)
{
echo "Asset Incomplete";
}
elseif($status==3)
{
echo "Yet to Start";
}
elseif($status==4)
{
echo "SME Discussion";
}
elseif($status==5)
{
echo "Development";
}
elseif($status==6)
{
echo "PB Review";
}
elseif($status==7)
{
echo "PB Fixes";
}
elseif($status==8)
{
echo "PB2 Review";
}
elseif($status==9)
{
echo "PB2 Fixes";
}
elseif($status==10)
{
echo "Alpha Development";
}
elseif($status==11)
{
echo "Alpha Review";
}
elseif($status==12)
{
echo "Alpha Fixes";
}
elseif($status==13)
{
echo "Beta Review";
}
elseif($status==14)
{
echo "Beta Fixes";
}
elseif($status==15)
{
echo "Gamma";
}
?></td>
<td><?php echo $report->coursename; ?></td>
<td><?php echo $report->statuscount;?></td>
<td></td>
</tr>
<?php
}
?>
</tbody>
Here is my controller:
public function index()
{
if ($this->session->userdata('is_logged')) {
$data['getCourse']=$this->Report_model->getTopicReports();
$this->load->view('template/header');
$this->load->view('reports/report',$data);
$this->load->view('template/footer');
}
else {
redirect("Login");
}
}
Here is my model:
public function getTopicReports()
{
$this->db->select('count(t.status) as statuscount,t.topicName as topicname,c.coursename,t.status')
->from('topics t')
->join('course c', 't.courseId = c.id')
->where('t.courseid',1)
->where('t.status',5);
$query = $this->db->get();
return $query->result();
}
This is how i want to display here is my referrence image:
Can anyone help me how to do that thanks in advance.
FINAL UPDATED & WORKING VERSION
For me this was tricky. This turned out to be what I felt to be a awkward indexing issue.
The problem is that your data is not optimized very well to accommodate the task you are asking for. You have to make odd comparisons as you traverse the table. I was able to get it accomplished.
I would actually be very interested in seeing a more refined approach. But until that happens this code will dynamically generate a table that matches the output of the sample pictures that you posted in your question.
I have tested this code with some sample data that matches the array structure that you posted in your comments.
Here is the code:
//Create an array with your status values.
$rowName = array(
'On Hold',
'Asset Incomplete',
'Yet to Start',
'SME Discussion',
'Development',
'PB Review',
'PB Fixes',
'PB2 Review',
'PB2 Fixes',
'Alpha Development',
'Alpha Review',
'Alpha Fixes',
'Beta Review',
'Beta Fixes',
'Gamma'
);
//Generate a list of class names and get rid of any duplicates.
foreach($getCourse as $report){
$courseNames[] = $report->coursename;
}
$courseNames = array_unique($courseNames);
//Create the header.
echo
'<table>
<thead>
<tr>
<th>#</th>';
foreach($courseNames as $course){
echo '<th>' . $course . '</td>';
}
echo
'<th>Total</th>
</tr>
</thead>
<tbody>';
//Iterate across the array(list) of status values.
for($i = 0; $i < count($rowName); $i++){
echo
'<tr>';
echo '<td>' . $rowName[$i] . '</td>';
//Iterate through all combinations of class names and status values.
for($j = 0; $j < count($courseNames); $j++){
//Set flags and intial values.
$found = FALSE;
$total = 0;
$value = NULL;
for($k = 0; $k < count($getCourse); $k++){
//***Note - The ""$getCourse[$k]->status - 1" is because the status values in your data do not appear
//to start with an index of 0. Had to adjust for that.
//Sum up all the values for matching status values.
if(($getCourse[$k]->status - 1) == $i){
$total += $getCourse[$k]->statuscount;
}
//Here we are checking that status row and the status value match and that the class names match.
//If they do we set some values and generate a table cell value.
if(($getCourse[$k]->status - 1) == $i && $courseNames[$j] == $getCourse[$k]->coursename){
//Set flags and values for later.
$found = TRUE;
$value = $k;
}
}
//Use flags and values to generate your data onto the table.
if($found){
echo '<td>' . $getCourse[$value]->statuscount . '</td>';
}else{
echo '<td>' . '0' . '</td>';
}
}
echo '<td>' . $total . '</td>';
echo
'</tr>';
}
echo '</tbody>
</table>';
Try this. I am storing course status in $used_status then displaying the remaining status which are not displayed in foreach.
$arr = array ( '1' =>'On Hold', '2' => 'Asset Incomplete', '3' => 'SME Discussion', '4' => 'a', '5' => 'b', '6' => 'c', '7' =>'d', '8' => 'e', '9' => 'f', '10' => 'g', '11' => 'h' );
$used_status = array();
foreach($getCourse as $report) { ?>
<tr>
<td>
<?php $course_status = isset($arr[$report->status]) ? $arr[$report->status] : "-";
echo $course_status;
$used_status[] = $course_status; ?>
</td>
<td>
<?php echo $report->coursename; ?>
</td>
<td>
<?php echo $report->statuscount; ?>
</td>
</tr>
<?php }
foreach($arr as $status) {
if(!in_array($status, $used_status)) { ?>
<tr>
<td>
<?php echo $status; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
<td>
<?php echo "-"; ?>
</td>
</tr>
<?php }
} ?>

PHP Multidimensional Arrays + array_key_exists not working correctly

Before i start to explain in details, let me show the screenshot of what I want the result to be.
What I want to achieve is quite simple, display all the items that are added to cart and calculate the total for each individual product. However, looks like my Multidimensional Arrays and array_key_exists didn't do it correctly and that's why didn't get the result i want.
As you can see from the screenshot, if the same product being added to cart, the quantity didn't plus 1 and it just display below the previous item.
products.php -> nothing special, just to display all the products in database
<?php
require 'config.php';
$q = mysqli_query( $db->conn(), "SELECT * FROM product" );
if( mysqli_num_rows($q) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc($q)){
//echo "id: " . $row["id"]. " <br>- Name: " . $row["product_name"]. " " . $row["product_price"]. "";
echo '<p>ID->'.$row['id'].' | '.$row['product_name'].' | $'.$row['product_price'].'
| Add to Cart</p>';
}
}
?>
cart.php
<?php
session_start();
if(isset($_GET['id'])){
require 'config.php';
$id=$_GET['id'];
$q = mysqli_query( $db->conn(), "SELECT * FROM product where id='$id'" );
$row = mysqli_fetch_assoc($q);
$product_name=$row['product_name'];
$product_price=$row['product_price'];
$quantity=1;
$total=$quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'][]=[]; //Create session 1st time
}
if(isset($_SESSION['cart'])){
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) { // list out all the items in Multi array
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
}
?>
May i know which part of the coding went wrong?
Revisiting the Code in your cart.php File would be of great Benefit here. Below is what you may want to consider:
<?php
$product_name = $row['product_name'];
$product_price = $row['product_price'];
$quantity = 1;
$total = $quantity*$product_price;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = [];
}
if(isset($_SESSION['cart'])){
// DOES THE PRODUCT ID EXIST IN THE $_SESSION['cart'] COLLECTION?
// IF IT DOESN'T WE CREATE IT AND LET IT BE...
if(!array_key_exists( $id, $_SESSION['cart'] )){
$_SESSION['cart'][$id] = [$id, $product_name, $product_price, $quantity, $total];
}else {
// IF IT ALREADY EXIST; WE SIMPLY GET THE OLD VALUES & APPEND NEW ONE TO IT...
// HERE YOU ASKED FOR array_key_exits($id, $_SESSION['cart']);
// WHICH MEANS $id MUST BE THE KEY HERE
// HERE IS WHERE THE PROBLEM IS....
$storedPrice = $_SESSION['cart'][$id][2];
$storedQuantity = $_SESSION['cart'][$id][3];
$storedTotal = $_SESSION['cart'][$id][4];
$_SESSION['cart'][$id] = [
$id,
$product_name,
$product_price,
$storedQuantity+1,
round( ($storedQuantity+1)*($product_price), 2),
];
}
echo '<table border="1" cellpadding="10">';
echo '<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>';
foreach ($_SESSION['cart'] as $key => $row) {
echo "<tr>";
foreach ($row as $key2 => $val) {
echo "<th>";
echo $_SESSION['cart'][$key][$key2]." ";
echo "</th>";
}
echo "</tr>";
}
echo '</table>';
}
You have made the mistake, when add a Cart and Update Cart:
So change the following line:
if(!array_key_exists($id,$_SESSION['cart'])){ // if item not in the cart then Add to cart and Quantity plus 1.
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}else {
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity++,$total];
}
Into
$find = false;
if(!empty($_SESSION['cart'])){
foreach($_SESSION['cart'] as $key=>$cart){
if(isset($cart[0]) && $cart[0] == $id){ //Already exists in Cart
$_SESSION['cart'][$key][3] = $_SESSION['cart'][$key][3] + 1; //$_SESSION['cart'][$key][3] is quantity
$_SESSION['cart'][$key][4] = $_SESSION['cart'][$key][3] * $_SESSION['cart'][$key][2] ; //$_SESSION['cart'][$key][4] update the total
$find = true;
}
}
}
if(!$find){ //Not in the Cart
$_SESSION['cart'][]=[$id,$product_name,$product_price,$quantity,$total];
}
Note: Before check, clear the cookies

how to make bill in php and sql

i have online shop and i have problem making the Bill for each order
let say someone buy 2 t-shart and 1 shoes it will add to the trolley table wich have prodcutid , usreid , Quantity , now if the user confirm the order how can i create bill with all the item he buy and save it to new database named bills
note that same user may have diffrent bill with different item
this is the code that display the orders and the total price
function CallMyOrder($identificador)
{
global $database_connectoos, $connectoos;
mysql_select_db($database_connectoos, $connectoos);
$query_CoryFuncion = sprintf("SELECT * FROM tbltrolley WHERE idUser = %s AND tbltrolley.intOrderDone = 1 , $identificador);
$CoryFuncion = mysql_query($query_CoryFuncion, $connectoos) or die(mysql_error());
$row_CoryFuncion = mysql_fetch_assoc($CoryFuncion);
$totalRows_CoryFuncion = mysql_num_rows($CoryFuncion);
?>
<?php
if ($totalRows_CoryFuncion > 0) { // Show if recordset not empty
echo " <li> User : ".CallUserName($row_CoryFuncion['idUser']);
$totalPrice =0;
$pricemultnumber;
do {
$pricemultnumber = $row_CoryFuncion['intQuantity'] * CallProductPrice($row_CoryFuncion['idProduct']);
echo "<li><br>";
echo "<img src='../document/product/".CallProductImage($row_CoryFuncion['idProduct'])."' border='0'/>";
echo "Product Name : ".CallProductName($row_CoryFuncion['idProduct']);
echo "<br>";
echo "Quantity : ".$row_CoryFuncion['intQuantity'];
echo "<br>";
echo "Price : ".$pricemultnumber." RM";
echo "<br></li>";
$totalPrice = $totalPrice + $pricemultnumber;
} while ($row_CoryFuncion = mysql_fetch_assoc($CoryFuncion));
echo "<br>";
echo "<p style='font-size: 24px; font-weight: bold;'>Tax : ".CallTax()."</p>";
$multp = (100 + CallTax())/100;
$totalPrice = $totalPrice * $multp;
echo "<p style='font-size: 24px; font-weight: bold;'>Total Price = ".$totalPrice." RM</p>";
}

How do I continually rename a variable in php?

I apologize in advanced because I believe that my question may be kind of confusing.
I have three different PHP files. The first one asks you how many different products you want (1-20) in which the variable is called $quantity. Once a number is selected from a drop down box, you are taken to the next PHP page that automatically generates a table with $quantity number of rows and in each row there is a dropdown box that is being populated from a database. There is also another column with empty textboxes for the quantity.
Here is the code for that:
<?php
$quantity = "";
$i = 1;
if (isset($_POST['quantity'])) {
$quantity= $_POST['quantity'];
$var = "";
while($row = mysqli_fetch_array($result1)){
$var = $var . "<option>" . $row['product_name'] . "</option>";
}
echo "<left><table border='1' width='1%'><tr><td><center>Product</td><td>Quantity</center></td></tr>";
while ($i <= $quantity){
echo "<tr><td><select name='product[]' size='1'>";
echo $var;
echo "</select></td><td><input name='quant[]' size='5' /></td></tr>";
$i++;
}
echo "</table></left>";
}
?>
Once each product and its desired quantity is entered, the user clicks submit and they are taken to the final PHP page. This PHP page is supposed to be a confirmation page with all of the customer information and their selected products and quantities. HOWEVER, my code is only printing out the LAST product and quantity in the table from the second PHP page. For example if the table is:
Product Quantity
Bed 1
Chair 2
Couch 3
My confirmation page prints out a one row table with ONLY the information for Couch instead of multiple rows with ALL three of those products. Here is my code for the last PHP page:
<body>
<?php
$curTime= "";
$customerbox= "";
$region= "";
$products = $_POST['product']; //I changed this (edit 2)
$quants = $_POST['quant']; //I changed this (edit 2)
if (isset($_POST['curTime'])) $curTime= $_POST['curTime'];
if (isset($_POST['customerbox']))$customerbox= $_POST['customerbox'];
if (isset($_POST['region']))$region= $_POST['region'];
if (isset($_POST['product']))$product= $_POST['product'];
if (isset($_POST['quant']))$quant= $_POST['quant'];
$error= false;
$done=false;
if ((isset($curTime) && empty($curTime))) {
print "Please enter the date.<br/>";
$error = true;
}
if (!isset($_POST['customerbox'])) {
print "Please select your customer.<br/>";
$error = true;
}
if (!isset($_POST['region'])){
print "Please select your region.<br/>";
$error = true;
}
if (!isset($_POST['product'])){
print "Please select your product.<br/>";
$error = true;
}
if ((isset($quant) && empty($quant))){
print "Please enter the quantity.<br/>";
$error = true;
}
else{
$error = true;
$done = true;
}
for ($i =0; $i < count($products); $i++){
echo $products[$i]; //I changed this
echo $quants[$i]; //I changed this
}
?>
<br>
<table style= border-collapse:collapse width="1%"border="2" align="center" <?php if (!$done){ echo "hidden";}?>
<tr>
<th>Date</th>
<th>Customer</th>
<th>Region</th>
<th>Product</th>
<th>Quantity</th>
</tr>
<tr>
<td><center><?php print $curTime?></td></center>
<td><center><?php print $customerbox?></td></center>
<td><center><?php print $region?></td></center>
<td><center><?php print $product?></td></center>
<td><center><?php print $quant?></td><center>
</tr>
</table>
</body>
I believe this problem is occurring because when I am creating the table with $quantity rows, it's continuously naming each dropdown box $product so it's taking the very last value as $product and printing that.
Is there anyway to print out all of the products with their respective quantities?
Thank you in advance!
For your product and quant dropdown boxes you should use name="product[]" and name="quant[]".
This will send an array instead of one value as $_POST variable, and you can then loop over this array by using
$products = $_POST[product];
$quants = $_POST[quant];
for ($i =0; $i < count($products); $i++){
echo $products[$i]; //echo one product
echo $quants[$i]; //echo one quantity
//etc..
}

Categories