I am learning PHP and trying to make a simple cart/processing script.
I have created the item cart fine, but I am having trouble displaying information in my receipt when a user commits to buying the item(s) in their cart.
To save space/time I have omitted my item lists and the generation of the cart, they can be found here if you need it.
Here is the PHP that posts the data to my checkout.php script
cart.php (Updated to reflect change)
<?php
session_start(); ?>
<form name="cart" id="cart" action="checkout.php" target='_blank'
method='post'>
<h1>Your Cart:</h1>
<table>
<tr>
<td><span class='title'>ID</span></td>
<td><span class='title'>Product</span></td>
<td><span class='title'>Price</span></td>
</tr>
<?php
// Set a default total
$total = 0;
foreach ( $_SESSION['cart'] as $cartid ) {
?>
<tr>
<td width="20%">
<?php echo $cartid; ?> <input type="hidden" name="id[]"
value="<?php echo $cartid; ?>">
</td>
<td width="100%">
<?php echo $title?>
<input type="hidden" name="title[]" value="<?php echo $title; ?>">
</td>
<td width="100%">$<?php echo $price;?>
<input type="hidden" name="prices[]" value="<?php echo $price; ?>">
</td>
</tr>
<?php
$total += $price;
} // end foreach
?>
<tr>
<td>Total</td>
<td></td>
<td>$<?php echo $total; ?></td>
</tr>
</table>
<input type="submit" value="Buy" class="submit-button" />
</form>
checkout.php (Updated to reflect change)
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<?php
foreach($_POST['ids'] as $id) {
echo "
<tr>
<td>$id</td>
<td>$_POST['titles'][$id]</td>
<td>$_POST['prices'][$id]</td>
</tr>
";
}
?>
<tr>
<td>Total</td>
<td></td>
<td>$</td>
</tr>
</table>
I cannot seem to get the foreach loop to read the item id, title, or price. I can see the array is being passed using print_r($_POST); but it is indexing each item as a new array item e.g:
Array
(
[checkout] => Array
(
[0] => A123
[1] => Item1
[2] => 1000
[3] => Z999
[4] => Item999
[5] => 9999
)
)
How can I post the information in a more meaningful way i.e. associated array. Then use that associated array to display information in a table like format?
Expected output
<table>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
</tr>
<tr>
<td>A123</td>
<td>Item1</td>
<td>$1000</td>
</tr>
<tr>
<td>Z999</td>
<td>Item999</td>
<td>$9999</td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td>$10999</td>
</tr>
</table>
N.B: This is just a learning exercise so array sanitizing not required, and no SQL.
Edit: Updated to reflect #Obsidian Age recommendations, getting parse error now
Your items all have the same name attribute in HTML:
<input type="hidden" name="checkout[]">
You would need three different named variables for submission, with one of them being the ID of the particular transaction:
<input type="hidden" name="ids[]">
<input type="hidden" name="titles[]">
<input type="hidden" name="prices[]">
Then you can loop through each item and add it to a corresponding array:
$titles = [];
$prices = [];
foreach($_POST['ids'] as $id) {
array_push($titles, $_POST['titles'][$id]);
array_push($prices, $_POST['prices'][$id]);
}
Or output it directly:
foreach($_POST['ids'] as $id) {
$title = $_POST['titles'][$id];
$price = $_POST['prices'][$id];
echo "
<tr>
<td>$id</td>
<td>$title<td>
<td>$price</td>
</tr>
";
}
Hope this helps! :)
Related
I am new to PHP(loving it already)
I have a form that looks up a table that sends 'golf hole' info back and allows a golfer to input their score of the hole. Problem I have is that I can present the first hole by looking up the hole_detail table but then cant figure out how loop through the table for hole 2, 3.....18 when the form is submitted. I have searched stackoverflow but cant find anything that specific about it. I have tried an if statement, if (isset($_POST['Submit'])) to try increment the $hole_id. Am I completely going about it the wrong way? Thanks in advance.
<?php
include ('../scripts/dbconfig.php');
# get the most recent course name:
$get_course_name = mysql_query("SELECT course_name FROM comp ORDER BY PID DESC LIMIT 1");
$show_course_name = mysql_fetch_array($get_course_name);
if (isset($_POST['Submit'])) {
$hole_id =1;
else {
$hole_id = $hole_id + 1;
}
}
# get the hole yardage and SI from most recent selected golf course:
$get_course_detail = mysql_query("SELECT * FROM `course_detail` WHERE course_name = '". $show_course_name['course_name'] . "'");
$show_course_detail = mysql_fetch_array($get_course_detail);
$get_hole_detail = mysql_query("SELECT * FROM `course_detail`,`phoenix_hole` WHERE Course_ID = 6 AND hole_id = $hole_id");
$show_hole_detail = mysql_fetch_array($get_hole_detail);
?>
</head>
<body>
<table width="300" cellspacing="0" cellpadding="0">
<tr>
<td width="40"><?php echo $show_course_name['course_name'];?></td>
</tr>
<tr>
<td width="20">HOLE <?php echo $show_hole_detail['hole_id']?></td>
<td width="5"> PAR <?php echo $show_hole_detail['hole_par'];?></td>
</tr>
<tr>
<td width="20">Yards</td>
<td width="20">S.I</td>
</tr>
<tr>
<td bgcolor="yellow"><?php echo $show_hole_detail['yellow_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td border="1px" bgcolor="white"><?php echo $show_hole_detail['white_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
<tr>
<td bgcolor="red"><?php echo $show_hole_detail['red_yards'];?></td>
<td><?php echo $show_hole_detail['hole_si'];?></td>
</tr>
</table>
</p>
<form id="game_form" name="game_form" method="post" action="game_form.php">
<table width="300" border="0" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>Hole Shots</b></td>
<td><input name="hole_shots" type="text" class="textfield" id="hole_shots" maxlength="2" size="3" ></td>
<td><b>Putts</b></td>
<td><input name="putts" type="text" class="textfield" id="putts" maxlength="2" size="3"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Next Hole" align="center" /></td>
</tr>
</table>
</form>
</body>
</html>
Or you can use a hidden field that keeps the hole number and you can increment it from php.
$hole_id, in this scenario, will always be 1, because when a user clicks the Submit button, $_POST['Submit'] will always have a value. What you should do instead is have $_POST['Submit'] contain the value of $hole + 1. PHP is not going to "remember" what $hole_id was last time around; it's up to you to remind it. As soon as a request is sent to the browser--unless you're using sessions--PHP forgets everything about that request (HTTP is "stateless").
<?php
if (isset($_POST['Submit'])) {
$hole_id = (int)$_POST['Submit'];
} else {
$hole_id = 1;
}
# other code here
?>
You are on hole #<?php echo $hole_id; ?>.
<form>
<!-- form stuff here -->
<button type="submit" name="Submit" value="<?php echo $hole_id + 1; ?>">Next hole</button>
</form>
I have a table called "project_name" in my database called "encrypt_decrypt". The table contains only 1 column called "name" which contains different values of name (ex : p1, p2, p3...). I have to retrieve this values(p1,p2,p3..) from my database and display it on a registration form with each value displaying one below the other having a checkbox with it so that user can select any of the name while registering! How do i do this in php ???
Thanks in advance!
<html>
<body>
<form name="reg" action="code_exec2.php" onsubmit="return validateForm()" method="post">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td><div align="right" style="white-space:nowrap" >Please select the project:</td>
</tr>
<tr>
<td><div align="right"><input type="checkbox" name="project[]" ></div></td>
<td><?php
session_start();
include('connection2.php');
$row=mysql_query("select * from project_name");
$array= array();
$output = mysql_fetch_assoc($row);
while($output){
$array[] = $output;
}
print_r($array);
?></td>
</tr>
<tr>
<td><div align="right"><input type="checkbox" name="Select all"
value="select all" onclick="toggle(this)"></div></td>
<td>Select all</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
Try this.
$result=mysql_query("select * from project_name");
$checkboxes=array();
while($r=mysql_fetch_assoc($result)){
$checkboxes[]='<input type="checkbox" name="names[]" value="'.$r['name'].'">'.$r['name'].'<br />';
}
Then echo below wherever you want the checkboxes to appear.
echo implode("\n",$checkboxes);
Assuming, that your connection to db is correct, you need to change the way you display results:
<?php
session_start();
include('connection2.php');
$row=mysql_query("select * from project_name");
$array= array();
while($output = mysql_fetch_assoc($row)){
//now you have row with name, and you need to display each name with new tr:
?>
<tr>
<td><div align="right"><input type="checkbox" name="project[]" value="<?php echo $output['name'] ?>"></div></td>
<td><?php echo $output['name'] ?></td>
</tr>
<?php } // closing while loop
?>
Note that I added value to checkbox - if you want to do something with checked project, you have to know which one it was.
And remember taht mysql_ functions are depreated! You should use PDO or mysqli_ instead
i tried this and i got: any ways thanks for all your help :)
<?php
include('connection.php');
$r=mysql_query("select distinct name from project_name");
$ProdArray=array();
while ($row = mysql_fetch_object($r)) {
array_push($ProdArray,$row->name);
}
foreach($ProdArray as $p) {
echo "<tr>";
echo "<td><div align='right'>";
echo "<input type='checkbox' name='project[]' value=" .$p. " />";
echo "</div></td>";
echo "<td>$p</td>";
echo "</tr>";
}
?>
I really need big help for this.
I have a form, and in that form client can choose country, and document type, and there is add to cart button.
So when the client select everything he need, all parametars are send into the session like this (this is in controller):
$quantity = 1; //this is default quantity for all documents
if(isset($_POST['cartBtn'])) {
if(!isset(Yii::app()->session['cart_values'])) {
Yii::app()->session['cart_values'] = array();
}
$sessionCart = Yii::app()->session['cart_values'];
$productInfo = Product::model()->find('id=:id',(array(':id'=>$_POST['documents'])));
$sessionCart[] = array('product_id' => $_POST['documents'], 'document' => $productInfo->name, 'countries'=>$_POST['countries'], 'quantity'=> $quantity, 'price' => $unitCost);
Yii::app()->session['cart_values'] = $sessionCart;
$this->redirect(array($this->id."/cart"));
}
after submiting the form the client is redirected to cart form, here in this form he can update the quantity of documents.
Now i have to determinate which column did the client select to update.
I try to do this in controller (under cart action) :
public function actionCart()
{
if(isset($_POST['cartBtnUpdate'])) {
$sessionCart['quantity'] = $_POST['quantity'];
}
$this->render('cart');
}
but when i do this nothing happened the value is 1, i enter 2 or 3 submit the form but value is 1.
Also I would like to delete the field if someone click the check box and submit the form, but i have no clue how to select the all session line to delete it.
Thanks.
Form code in cart view:
<?php
if (is_array(Yii::app()->session['cart_values']))
{
$total = 0;
foreach ( Yii::app()->session['cart_values'] as $value) {
$total += $value['price'];
?>
<tr id="TDcartTable">
<td class="docName">
<?php echo $value['document'] ?>
</td>
<td>
£ <?php echo number_format($value['price'], 2); ?>
</td>
<td>
<?php echo CHtml::textField('quantity', $value['quantity']); ?>
</td>
<td>
£ <?php echo number_format(($value['price'] * $value['quantity']), 2);
?>
</td>
<?php }
}
?>
<td>
</td>
</tr>
<tr>
<td class="column-last" colspan="6">
</td>
</tr>
<tr>
<td class="cart-order-total" colspan="6">
<?php echo CHtml::encode(Yii::t('app', 'Order Total')); ?>: £ <?php echo number_format($total, 2); ?>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="button" name="cartBtnUpdate" value="<?php echo CHtml::encode(Yii::t('app', 'Update Your Shopping Cart')); ?>">
</td>
<td colspan="4">
<input type="submit" class="button" name="cartBtnContinue" value="<?php echo CHtml::encode(Yii::t('app', 'Continue')); ?>">
</td>
</tr>
The variable $sessionCart is not defined in your controller action before you attempt to use it. You need to define it:
if (isset($_POST['cartBtnUpdate'])) {
$sessionCart = Yii::app()->session['cart_values'];
$sessionCart['quantity'] = $_POST['quantity'];
}
I am having problem in this situation, i searched alot and don't know what should i do with it....
I have got like 4 checkboxes, on each checkbox a certain function is being performed. I have this html code for checkboxes,
<form action="check.php" method="post">
<table border="1" width="200">
<tr>
<td>
<input type="checkbox" name="first[]" value="option1" />
</td>
<td width="500">
<strong>Option 1</strong>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="first[]" value="option2" />
</td>
<td width="500">
<strong>Option 2</strong>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="first[]" value="option3" />
</td>
<td width="500">
<strong>option 3</strong>
</td>
</tr>
</table>
<table border="1" width="200">
<tr>
<td>
<input type="text" name="entered_value"/>
</td>
</tr>
</table>
<table border="1" width="200">
<tr>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
I am accessing these checkboxes using this code
<?php
if (isset($_POST['submit']))
{
if(isset($_POST['first']))
{
$get_data_checkboxes = $_POST['first'];
}
else
{
$get_data_checkboxes = "";
}
print_r($get_data_checkboxes);
exit();
}
?>
What i am facing problem is like i need to run a function on each checkbox ticked, e.g. if the person ticks Option 1 then i should be able to run function 1 and so on...
any help will be appreciated :)
If you want to select multiple checkboxes, you can try something like this:
for( $i = 0; $i < count( $_POST['first'] ); $i++ ) {
if( $_POST['first'][$i] == 'option1' ) {
echo "function1";
} else if( $_POST['first'][$i] == 'option2' ) {
echo "function2";
} else if( $_POST['first'][$i] == 'option3' ) {
echo "function3";
}
}
You don't need the line
if (isset($_POST['submit']))
Without that your code works fine, and you can use that to call your functions like this:
<?php
if(isset($_POST['first']))
{
$get_data_checkboxes = $_POST['first'];
foreach($get_data_checkboxes as $value){
//call functions named option1(), option2(), etc..
call_user_func($value);
}
}
else{
$get_data_checkboxes = "";
}
?>
I need to pass back a large string of results to a form, so that the form can read those results from the URL and then populate the form with them. Problem is, the link ends up being:
&key=value&key=value ... until it can't process anymore (I assume a URL has a length limit?) resulting in my form not being able to fully populate. I need another way to pass values back to my form file.
VIEW.php file (basically just a table of values right as they are from the database, with the first column "id" being a link. When I click on "id", it goes back to my add.php(form page) and populates the form with the data matching that id)
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETED</th>
<th></th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// loop to fetch data
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='molszewski1_a2_add.php'>$row[id]</a></td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td>$row[deleted]</td>";
$status = "$row[deleted]";
echo "<td><a href='molszewski1_a2_delete.php?id=$row[id]&flag=$status&sort=$sort'>";
$status = "$row[deleted]";
if ($status == 'n') {
$flag = "restore";
echo "delete";
} else if ( $status == 'y') {
$flag = "delete";
echo "restore";
}
echo "</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
ADD.php (form page where the form is supposed to fetch the data and populate it)
<?php
// If no form has been submitted, present form
if (empty($_GET))
{
add_form();
}
// if a form has been submitted
else
{
// if form_validity() == 1, proceed to connect
if (form_validity() == 1)
{
// connect to mysql + database
connect();
$saleItem = "n";
$discountItem = "n";
if( array_key_exists( 'saleItem', $_GET ) && $_GET['saleItem'] == 'y' )
{ $saleItem = "y"; }
if( array_key_exists( 'discountItem', $_GET ) && $_GET['discountItem'] == 'y' )
{ $discountItem = "y"; }
// get values from form, insert into database
$sql=("INSERT INTO inventory (name,
manufac,
model,
descrip,
onhand,
reorder,
cost,
price,
sale,
discont,
deleted)
VALUES ('$_GET[itemName]',
'$_GET[manufacturer]',
'$_GET[model]',
'$_GET[description]',
'$_GET[numberOnHand]',
'$_GET[reorderLevel]',
'$_GET[cost]',
'$_GET[sellingPrice]',
'$saleItem',
'$discountItem', 'n')");
// if the query doesn't work, display error message
if (!(mysql_query($sql))) { die ("could not query: " . mysql_error()); }
add_form();
// redirect to view.php after form submission
// use php instead
echo "<meta http-equiv='REFRESH' content='0;url=molszewski1_a2_view.php'>";
}
else
{
// if form is not valid (form_validity returns 0), display error messages
add_form();
}
}
?>
FUNCTIONS.php (all my functions for stuff like the form)
<?php function page_navigation(){ ?>
<div class="center">
<input type="button" value="ADD" />
<input type="button" value="VIEW" />
<input type="button" value="VIEW DELETED" />
<input type="button" value="VIEW ACTIVE" />
<br />
<br />
</div>
<?php } ?>
<?php function add_form() { ?>
<form action="molszewski1_a2_add.php" method="get" id="form">
<table width="529px">
<tr>
<td>ITEM NAME</td>
<td><input name="itemName" size="30" type="text" value="<?php echo $_GET["itemName"] ?>"/></td>
</tr>
<tr>
<td>MANUFACTURER</td>
<td><input name="manufacturer" size="30" type="text" value="<?php echo $_GET["manufacturer"] ?>"/></td>
</tr>
<tr>
<td>MODEL</td>
<td><input name="model" size="30" type="text" value="<?php echo $_GET["model"] ?>"/></td>
</tr>
<tr>
<td>DESCRIPTION</td>
<td><textarea name="description" rows="3" cols="20"><?php echo $_GET["description"] ?></textarea></td>
</tr>
<tr>
<td>ON HAND</td>
<td><input name="numberOnHand" size="30" type="text" value="<?php echo $_GET["numberOnHand"] ?>"/></td>
</tr>
<tr>
<td>REORDER LEVEL</td>
<td><input name="reorderLevel" size="30" type="text" value="<?php echo $_GET["reorderLevel"] ?>"/></td>
</tr>
<tr>
<td>COST</td>
<td><input name="cost" size="30" type="text" value="<?php echo $_GET["cost"] ?>"/></td>
</tr>
<tr>
<td>SELLING PRICE</td>
<td><input name="sellingPrice" size="30" type="text" value="<?php echo $_GET["sellingPrice"] ?>"/></td>
</tr>
<tr>
<td>SALE ITEM</td>
<td>
<input type="checkbox" name="saleItem" value="y" <?php if( isset( $_GET['saleItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td>DISCOUNTED ITEM</td>
<td>
<input type="checkbox" name="discountItem" value="y" <?php if( isset( $_GET['discountItem'] ) ){ ?> checked="checked" <?php } ?> />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="save" name="submit" id="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Use method="post" and $_POST (instead of $_GET).
POST requests can be much larger than GET requests as GET requests are limited by the maximum length of a URL. POST requests are limited by the size of the max_post_size ini-value which is usually a few megabytes.