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..
}
Related
I want to display checked checkbox which are stored as values in a mysql database.
For now the table stores the value of the checkbox being checked in the database. The header and first column are fetched from three different tables in the database. While the values of the checked check-boxes gets saved in a same table.
Here's the code for inserting the data.
$active = "CourseReport";
require_once 'pages/header.php';
require_once './functions/schema-functions.php';
require_once './functions/report-functions.php';
$course = Schema::getCourseReport();
$objective = Schema::getObjective();
$goals = Schema::getGoals();
$mainobj = Schema::getMainObjectives();
$subobj = Schema::getSubObjectives();
?>
<form id="addReport" action ='./functions/report-functions.php' method="post">
<table id="table1" class="table table-hover">
<thead>
<?php
echo '<tr><th>Goals</th>';
for ($i = 0; $i < count($course); $i++) {
echo '<th id = "rotate1">'. $course[$i]->commonName . '</th>';
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
for ($y = 0; $y < count($goals); $y++) {
echo '<tr class="clickable"><th class="toggle">Goal#'.$goals[$y]['GoalId'].':'." " .' '.$goals[$y]['Goals'].'</th>
</tr>';
?>
<?php
for( $z = 0; $z < count($mainobj); $z++){
if($mainobj[$z]['GoalId'] == $goals[$y]['GoalId']) {
echo '<tr class="expander"><th class=row-header>Objective#'.$mainobj[$z]['MainObjId'].':'." ".' '.$mainobj[$z]['MainObjectives'].'</th>
</tr>';
?>
<?php
for ($j = 0; $j< count($subobj); $j++) {
if($mainobj[$z]['MainObjId'] == $subobj[$j]['MainObjId']){
echo '<tr class="expander"><td class=row-header>'.$subobj[$j]['SubObjId'].' ) '.$subobj[$j]['SubObjectives'].' </td>';
for ($x = 0; $x < count($course); $x++) {
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
}
echo '</tr>';
}
}
}
}
}
?>
</tbody>
</table>
<button class="button" name= "submit" value= "Submit">Submit</button>
</form>
report-functions.php
if( isset( $_POST['submit'], $_POST['check'] ) ){
try{
require_once 'db-connect.php';
$conn = DatabaseConnection::getConnection();
$sql= " insert into `Report` (`ColRow`) values (:value) ";
$stmt = $conn->prepare( $sql );
if( $stmt ){
$conn->beginTransaction();
foreach( $_POST['check'] as $index => $value ) {
$result = $stmt->execute( [ ':value' => $value ] );
if( !$result ) {
echo '
<script>
alert("Error, please try submitting again. Error code 1");
window.history.back();
</script>';
}
}
$conn->commit();
echo '<script>
alert("Report was submitted successfully.");
window.location = ".../";
</script>';
}
} catch( Exception $e ){
$conn->rollback();
exit( $e->getMessage() );
}
I expect that once I submit the table, the table should load the same table with the checked checkboxes. I should be able to make the changes and submit the table over and over again.
Please comment if I need to provide any additional information.
When you display your page (in your first section of code), at some point you do this:
echo "<td><input name='check[]' type=checkbox value=c".$course[$x]->courseId."-o".$subobj[$j]['SubObjId']." id=checked></td>";
The value is set to:
value=c"c.$course[$x]->courseId."-o".$subobj[$j]['SubObjId']";
This value is where you get the checked or not value you mentioned in the comments (like c1-o1.1).
Right. So before you do that echo, add a new if condition.
$value = "c$course[$x]->courseId" . "-o$subobj[$j]['SubObjId']";
if (verify_checked($value)) {
$checked_code = "checked=\"checked\"";
}
else {
$checked_code = "";
}
echo "<td><input name='check[]' type=checkbox value=$value id=checked $checked_code ></td>";
The verify_checked(value) function does (from what I understand of your database, you keep the "grid location" of checked elements):
function verify_checked($value)
{
// Connect to the database if needed
// Perform: SELECT count($value) FROM Report
// If the result is >0, return TRUE
// Else return FALSE
}
The idea here is to query the database every time your are about to echo the <input> element.
Note for concatenating text, I find it more legible to put spaces around the . to clearly split what is part of the text and what is the concatenation dot.
As mentioned previously, indentation is critical for understanding of the different contexts. Until I indented your code, I had not realized how the different loops worked in relation to the others.
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
I have a page which generates a list of games and button for each game with value "BUY GAME".
The objective is to execute multiple SQL queries when the button is clicked for a particular game.
What is an appropriate way of accessing the 'name','consolename',etc. for EACH game from the ARRAY and to execute queries on them in another page - purchase.php?
NOTE: I did consider using sessions but when I pass the variable $index as a SESSION variable, I only get the final value at all times.
buygame.php
<?php
session_start();
//connect to db
dbConnect("root", "") ;
dbSelect("webdesign");
//SEARCH FOR GAMES
print "<h3>Games to Buy: </h3>";
$query = "SELECT gamecode,name, consolename,price, points, genre from game";
$result = runQuery($query);
while($row = mysql_fetch_array($result))
{
$array[] = $row;
}
$index =0 ;
//DISPLAYING A LIST OF GAMES
while($index<sizeof($array))
{
echo $array[$index]['name'];
echo $array[$index]['consolename'];
echo $array[$index]['genre'];
echo ("Price is: ".$array[$index]['price']." USD");
echo ("Loyalty Points: ".$array[$index]['points']);
//THE BUTTON "BUY GAME"
echo("<a href='purchase.php'><input type='submit' name='submit[$index]' value='Buy Game'/></a>");
$index = $index + 1;
}
?>
purchase.php
<?php
session_start();
//connect to database
dbConnect("root", "") ;
dbSelect("webdesign");
$index = 0;
echo "Button clicked ";
//I am trying this but I'm sure that this is not right
if (isset($_POST['submit[$index'])){
print "$index was clicked";
}
?>
In buygame.php change the code to:
//THE BUTTON "BUY GAME"
echo("<a href='purchase.php?gamecode={$array[$index]['gamecode']}'><input type='submit' name='submit[$index]' value='Buy Game'/></a>");
In purchase.php
<?php
if(isset($_GET['gamecode'])) {
echo $_GET['gamecode'];
//and make ......
}
//THE BUTTON "BUY GAME"
$gamecode = $array[$index]['gamecode'];
echo("<a href='purchase.php?gamecode=$gamecode'><input type='submit' name='submit[$index]' value='Buy Game'/></a>");
$index = $index + 1;
Then in purchase.php You know exactly, what game has been bought.
I have a simple php checkout but when adding the product to basket i get the following error:
PHP Notice: Undefined offset: 36 in C:\inetpub\wwwroot\shopping\cart.php on line 76
If i then refresh the page or go back to add another product it displays a product fine, it seems to be when adding to first product to the cart we get this error. any help would be much appreciated as all the answers i have tried have not worked.
<?php
// connect to the database
include("databasedrop.php");
?>
<div class="post">
<h2>Shopping Basket<span class="title-bottom"> </span></h2>
</div>
<!-- End Post -->
<?php
if (empty($_GET['id'])) {
$_GET['id'] = "";
}
$ProductID = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
switch ($action) { //decide what to do
case "add":
$_SESSION['cart'][$ProductID] ++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$ProductID] --; //remove one from the quantity of the product with id $product_id
if ($_SESSION['cart'][$ProductID] == 0)
unset($_SESSION['cart'][$ProductID]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if (empty($_SESSION['cart'])) {
$_SESSION['cart'] = "";
}
if ($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" padding=\"3\" width=\"40%\">"; //format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach ($_SESSION['cart'] as $ProductID => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
if ($stmt = $conn->prepare("SELECT * FROM products WHERE ProductID=?")) {
$stmt->bind_param("i", $ProductID);
$stmt->execute();
$stmt->bind_result($ProductID, $Title, $Description, $Price, $Stock, $Image, $Category, $Status);
$stmt->fetch();
// show the form
}
$total = "";
$line_cost = $Price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$Title</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">$total</td>";
echo "</tr>";
//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
} else {
//otherwise tell the user they have no items in their cart
echo "You have no items in your shopping cart.";
}
?>
Shot in the dark, but only solution I can see.
Do you ever create the $_SESSION['cart']-array?
Try this:
switch ($action) {
case "add":
if (!isset($_SESSION['cart'][$ProductID])) {
$_SESSION['cart'][$ProductID] = 1;
}
else {
$_SESSION['cart'][$ProductID]++;
}
break;
I am trying to work my head round this, I am using the following code to check the answers to a quiz and output either CORRECT or INCORRECT depending on the result of the comparison, and if the answer field is black (which only comes from the feedback form) a different message is displayed.
I cant quite work out how to apply the php count function in this situation though, what im trying to get it to do it count the amount of CORRECT and INCORRECT answers and add the two together, and then I can work out a % score from that.
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.questionID = q.questionID ORDER BY a.cf_id ASC" or die("MySQL ERROR: ".mysql_error());
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}}
?>
Iv found this example and have been trying to work out how to work it in, but cant think how to count the results of an if statement with it ?.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>
Just increment two counters
$correct_answers = 0;
$incorrect_answers = 0;
while ($row = mysql_fetch_array($result)) {
if ($row['correctanswer'] == '') {...
} elseif ($row['correctanswer'] == $row['quizselectanswer']) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$correct_answers++;
} else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$incorrect_answers++;
}
}
Simply increase some counter in each branch of your if/elseif/else construct...
$counters = array( 'blank'=>0, 'correct'=>0, 'incorrect'=>0 );
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ( ''==$row['correctanswer'] ) {
echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';
$counters['blank'] += 1;
}
elseif ( $row['correctanswer']==$row['quizselectanswer'] ) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$counters['correct'] += 1;
}
else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$counters['incorrect'] += 1;
}
}
echo '#correct answers: ', $counters['correct'];
How about creating a variable with a count of correct answers? For each question you loop through, increment the value by one.
<?php
$correct_answers = 0;
while($questions) {
if($answer_is_correct) {
// Increment the number of correct answers.
$correct_answers++;
// Display the message you need to and continue to next question.
}
else {
// Don't increment the number of correct answers, display the message
// you need to and continue to the next question.
}
}
echo 'You got ' . $correct_answers . ' question(s) right!';
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT ... ";
$result = mysql_query($query) or die(mysql_error());
$countCorrect = 0;
$countIncorrect = 0;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
$countCorrect++;
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {
$countIncorrect++;
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}
}
echo ((int)($countCorrect/($countIncorrect + $countCorrect) * 100)) . "% answers were correct!" ;
?>