Disabling checkout button from shopping cart - php - php

I am trying to setup a “view shopping cart/basket” page within a site in which logged in users earn points/credits. Once they earn a certain amount of these points they can then go to a shopping cart and pay with these points only. (No money changes hands, so no paypal/checkout/shipping/taxes etc are involved)
So far I have got the login, points total table, add product to cart and change of quantity feature to work.
What I am trying to do on this ‘view_cart.php’ page (code below) is to make the ‘Checkout’ link (submit_cart.php) disappear or be disabled if the user's points total is less than the total shopping cart price. Is there anyway I can do this on this script?
The ‘You don’t have enough points to proceed to checkout’ prompt works if this is the case but if I can this checkout link to disappear that would be great.
My php knowledge is limited as I’m more of a front end designer but please feel free to offer any suggestions or changes of approach.
Thanks!
<?php
$page_title = 'Your Rewards Shopping Cart';
include ('./includes/header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1);
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
$rwp = $_SESSION['reward_user_points'];
$problem = FALSE;
if (isset($_POST['submitted']))
{
foreach ($_POST['qty'] as $k => $v) {
$pid = (int) $k;
$qty = (int) $v;
if ( $qty == 0 ) {
unset ($_SESSION['cart'][$pid]);
} elseif ( $qty > 0 ) {
$_SESSION['cart'][$pid] ['quantity'] = $qty;
}
} // End of FOREACH.
} // End of SUBMITTED IF.
$empty = TRUE;
if (isset ($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $key =>$value) {
if (isset($value)) {
$empty = FALSE;
break; // Leave the loop.
}
} // End of FOREACH.
} // End of ISSET IF.
if (!$empty) {
require_once ('/MySQL/database.php');
$query = "SELECT users_id, reward_user_points FROM reward_points
WHERE reward_points.users_id = users.users_id";
$result = mysql_query($query);
$query = "SELECT products_id, products_name FROM categories, products
WHERE categories.categories_id = products.categories_id AND products.products_id
IN (";foreach ($_SESSION['cart'] as $pid =>$value) {
$query .= $pid . ',';
}
$query = substr ($query, 0, -1) . ') ORDER BY categories.categories_name ASC';
$result = mysql_query($query);
?>
<h1>Your Shopping Cart</h1>
<div id="sidebar">
<div id="statusbar">
<p><span class="statusbar_highlight">Name:</span><br />
<?php echo " {$_SESSION['users_first_name']} " . " {$_SESSION['users_surname']}<br> ";?></p>
<p><span class="statusbar_highlight">Outlet:</span><br />
<?php echo " {$_SESSION['users_outlet']} ";?></p>
<p><span class="statusbar_highlight">Sales Number:</span><br />
<?php echo " {$_SESSION['users_sales_no']} ";?></p>
<p><span class="statusbar_highlight">My Points:</span><br />
<font size="+1"><?php echo " {$_SESSION['reward_user_points']} ";?></font></p>
</div>
<br /><br /><br /><br /><br /><br /><br /><br />
</div>
<div id="maincontent_inner">
<div id="maincontent_inner2">
<?php
echo '<table border="0" width="100%" cellspacing="1" cellpadding="5" align="center">
<tr class="top">
<td align="left" width="46%"><b>Reward Product</b></td>
<td align="right" width="18%"><b>Price</b></td>
<td align="center" width="16%"><b>Qty</b></td>
<td align="right" width="20%"><b>Sub Total</b></td>
</tr>
<form action="view_cart.php" method="post">';
$total = 0; // Total cost of the order.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
// Total and subtotals.
$subtotal = $_SESSION['cart'][$row
['products_id']]['quantity'] *
$_SESSION['cart'][$row ['products_id']]['price'];
$total += $subtotal;
if ($rwp >= $total) {
}
else {
echo "You do not have enought points to proceed to checkout <br />";
}
// Print the row.
echo " <tr>
<td align=\"left\">{$row['products_name']}</td>
<td align=\"right\">{$_SESSION['cart'][$row['products_id']] ['price']} pts</td>
<td align=\"center\"><input type=\"text\" size=\"3\"
name=\"qty[{$row['products_id']}]\"
value=\"{$_SESSION['cart'][$row['products_id']]['quantity']}\" /></td>
<td align=\"right\">" . number_format ($subtotal) . " pts</td>
</tr>\n";
} // End of the WHILE loop.
mysql_close($dbc); // Close the database connection.
// products the footer, close the table, and the form.
echo ' <tr class="even">
<td colspan="3" align="right"><b> TOTAL:<b></td>
<td align="right"><b>' . number_format ($total) . ' pts </b></td>
</tr>
</table>
<br />
<div align="center"><input type="submit" name="submit"
value="Update" />
<input type="hidden" name="submitted"value="TRUE" />
</form><br /><br /></div>
<p><img src="images/but_continue.png" /></p>
<p><img src="images/but_checkout.png" /></p>';
} else {
echo '<h1>Shopping Cart</h1><p>Your cart is currently empty.</p>
<p><img src="images/but_continue.png" /></p>
<div id="maincontent_inner">
<div id="maincontent_inner2"> ';
}
?>
<br />
<p>
<span class="extras"><strong>Please Note the following:</strong><br />
1. To delete any item off your cart, simply type in '0' and click 'Update'<br />
2. To add in more than one item, simply click the desired amount and click 'Update'<br />
3. Your cart will be emptied upon logging out of your session<br />
</span></p>
</div>
</div>
</div>
</div>
<?php
include ('./includes/footer.html');
?>

It looks to me like you're darn close:
if ($rwp >= $total) {
echo '<button>Checkout</button>'; //Just put the code you want here
}
else {
echo "You do not have enought points to proceed to checkout <br />";
}
In your sample, these lines are in the while which will cause a problem. Just move them out to where you want this to display and you're on your way.

$str = '<tr class="even">
<td colspan="3" align="right"><b> TOTAL:<b></td>
<td align="right"><b>' . number_format ($total) . ' pts </b></td>
</tr>
</table>
<br />
<div align="center"><input type="submit" name="submit" value="Update" />
<input type="hidden" name="submitted"value="TRUE" />
</form><br /><br /></div>
<p><img src="images/but_continue.png" /></p>
<p><img src="images/but_checkout.png" /></p>';
if($rwp >= $total) {
$str .='<img src="images/but_checkout.png" /></p>';
}
else {
$str .='<p>You donnot have enough points to buy</p>';
}
echo $str;
Use the above code instead of the code bellow the following comment in your code
// products the footer, close the table, and the form.

Related

How do you "transfer" a dynamic value from one php page to another php page?

How can you pass dynamic details which are retrieved from a database (e.g. details in a shopping cart table) from one page to another page so that you could send them via email using the mail() function?I tried many ways using the "$message" but none worked. I am new to PHP and do not have much experience with it yet. Any help would be appreciated, thank you.
page 1:
<?php session_start();
//starting the session
include("adminarea/includes/DBcon.php");
include ("functions/php1.php");
include ("header.php");
require 'obj.php';
?>
<link rel="stylesheet" href = "styles/styling.css" media="all" />
<body>
<?php
//Fetches information from the database and displays them with the help of obj.php
if(isset($_GET['pID'])){
$res = mysqli_query($connection, 'select * from product where pID='.$_GET['pID']);
$prod = mysqli_fetch_object($res);
$obj = new obj();
$obj->pID = $prod->pID;
$obj->pName = $prod->pName;
$obj->pPrice = $prod->pPrice;
$obj->qty = 1;
//to check if products exists in cart or not
$index = -1;
$cart = unserialize(serialize($_SESSION['cart']));
for($i=0;$i<count($cart);$i++)
if($cart[$i]->pID==$_GET['pID'])
{
$index = $i;
break;
}
if($index==-1)
$_SESSION['cart'][] = $obj;
else{
$cart[$index]->qty++;
$_SESSION['cart']=$cart;
}
echo "
<script>
window.open('cart.php','_self')
</script>
";
$_SESSION['pID'] = $_POST['pID'];
$_SESSION['pName'] = $_POST['pName'];
$_SESSION['pPrice'] = $_POST['pPrice'];
$_SESSION['qty'] = $_POST['qty'];
}
if(!(isset($_SESSION['cart']))){
echo "
<script>
alert('Shopping cart is empty!')
window.location.href='index.php';
</script>
";
}
//if statement to delete the chosen product inside the cart
if(isset($_GET['index']))
{
$cart = unserialize(serialize($_SESSION['cart']));
unset ($cart[$_GET['index']]);
$cart = array_values($cart);
$_SESSION['cart'] = $cart;
}
?>
<!-- This is to display the shopping cart table-->
<table cellpadding="5" cellspacing="4" border ="9" align="center" width="100%" border="9" bgcolor="darkred">
<td style="color:#FFF" colspan="10" align="center"><h2><u><i>Shopping Cart:</i></u></h2>
<tr>
<th style="color:#FFF">Option</th>
<th style="color:#FFF">Id</th>
<th style="color:#FFF">Name</th>
<th style="color:#FFF">Price</th>
<th style="color:#FFF">Quantity</th>
<th style="color:#FFF">SubTotal</th>
</tr>
<?php
$cart = unserialize(serialize($_SESSION['cart']));
$s = 0;
$index = 0;
for($i=0; $i<count($cart); $i++){
$s += $cart[$i] ->pPrice * $cart[$i]->qty;
?>
<tr>
<td>
<div class="shopcart">
<input id="input" type="submit" name="ctable"/>Remove</input></td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->pID; ?> </td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->pName; ?></td>
<td style="color:#FFF" align="center">€<?php echo $cart[$i] ->pPrice; ?></td>
<td style="color:#FFF" align="center"><?php echo $cart[$i] ->qty; ?></td>
<td style="color:#FFF" align="center">€<?php echo $cart[$i] ->pPrice * $cart[$i]->qty;?></td>
</tr>
<?php }
$index++;
?>
<tr>
<td colspan="5" align="right" style="color:#FFF">Total</td>
<td style="color:#FFF" align="center">€<?php echo $s;?></td>
</tr>
</table>
<br>
<a id="a" style="margin-left: 10px;" href="products.php"> Go back</a><br><br>
<div id="checkout">
<form id="checkout" method="post" action="checkout.php">
<input id="input" type="submit" name="check" value="Checkout" style="background-color:gray; width:200px; margin-right: 10px;">
</div>
</div>
<?php include("footer.php") ?>
</body>
</html>
page 2:
<?php session_start();
require 'obj.php';
include("adminarea/includes/DBcon.php");
$to = "techologyy#gmail.com";//direction
$subject = "Purchase Details:";
$message = $_SESSION['pID'];
$message .= $_SESSION['pName']."\r\n";
$message .= $_SESSION['pPrice']."\r\n";
$message .= $_SESSION['qty']."\r\n";
$headers = 'From: techologyy#gmail.com' . "\r\n"; //from
//mail paramter with correct order
mail($to, $subject, $message, $headers);
//echo to display alert
echo "
<script>
alert('The checkout has been done successfully! Thank you')
window.location.href='index.php';
</script>
"; //returns the user back to homepage
?>
Please specify what you have tried so far.
you want to send the data from one page to another, try using form tag in html
and set the method attribute to post and action attribute to where you want to send the data.
The html code will look like this
<form action="post" action="getdata.php"> <input id="val" type="text" value="" name="cart" style="display:none;"> <button type="submit" >hit me</button> </form>
You can set the value of input using javascript
document.getElementById("val").value="YourValue";
getdata.php will look like this
> if ($_SERVER["REQUEST_METHOD"] == "POST"){
> $cartval=$_POST['cart'];
> echo $cartval; }
be sure to validate the data and check for any hidden code before executing the user input

Add items in shopping basket to database

I am trying to insert the items in the shopping basket to the table userOrders within my database. The fields in Mysql are productId, Quantity and orderTotal I am aware that I should be using SSL.
I am relatively new to this so please be kind to me, any help would be greatly appreciated.
the shopping basket:
<h1>View Shopping Basket</h1>
<div class="container-fluid">
<div class="row">
<div class="col-lg-6">
<form method="post" value="placeOrder" action="<?php echo
htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<form method="post" value="update" action="checkout.php?
page=cart">
<table class="table-responsive">
<thead>
<tr>
<th>productId</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<?php
//select all from products where ID is in session
$sql="SELECT * FROM products WHERE productId IN (";
//for each session append ID and add comma's to seperate
foreach($_SESSION['cart'] as $id => $val) {
$sql.=$id.",";
}
//subtract last comma from ID's & append last bracket to
prevent error
$sql=substr($sql, 0, -1).") ORDER BY name ASC";
$query=mysql_query($sql);
$totalprice=00.00;
$quantity =0;
$productId = 'productId';
while($row=mysql_fetch_array($query)){
//running total
$subtotal=$_SESSION['cart'][$row['productId']]
['quantity']*$row['price'];
//total price added with each loop
$totalprice+=$subtotal;
?>
<tbody>
<tr>
<!--hidden productId-->
<td><?php echo $row['productId'] ?></td>
<!--display product name-->
<td><?php echo $row['name'] ?></td>
<!--display quantity-->
<!--take 'productID' & 'quantity' rows, -->
<td><input type="text" name="quantity[<?php echo
$row['productId'] ?>]" size="2" value="<?php echo $_SESSION['cart']
[$row['productId']]['quantity'] ?>" /></td>
<!--display price-->
<td><?php echo $row['price'] ?>£</td>
<!--products price == quantity of productID in
session * price -->
<td><?php echo $_SESSION['cart'][$row['productId']]
['quantity']*$row['price'] ?>£</td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" style="text-align:right">Total Price: <?
php echo $totalprice ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<br />
<button type="submit" value="update" name="update">Update Shopping
Basket</button>
<br />
<button type="submit" value="PlaceOrder" name="PlaceOrder">Place
Order</button>
</form>
<br />
<p style="text-align:center">To remove an item set its quantity to 0. </p>
<a href="shopsesh.php?page=products"><p style="text-align:left">Continue
Shopping</a></p>
Update Quantity:
<?php
//check form was submitted, if yes & value ==0 then unset session.
if(isset($_POST['submit'])){
foreach($_POST['quantity'] as $key => $val) {
if($val==0) {
unset($_SESSION['cart'][$key]);
//if form was submit and value =! 0 then update quantity
}else{
$_SESSION['cart'][$key]['quantity']=$val;
}
}
}
?>
Insert Query:
<?php
//add items to orders table in DB
if (isset($_POST['placeOrder'])) {
//if no error
if( !$error ) {
$productId = $_POST['productId'];
$quantity = $_POST['quantity'];
//$_POST['$totalPrice'];
//insert order into database
$query = "INSERT INTO userOrders(productId,quantity,orderTotal)
VALUES('$productId','$quantity','$totalprice')";
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Items added to database";
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
?>

php issues adding product to shopping cart

I'm having issues adding products to my shopping cart. In order to read it easier I'm only posing the php code. I'm not worried about security issues at this point, just looking to correct the issue with the product not showing up in the cart on the page view_cart.php . Can anyone see what I'm missing here? Also, the session is started on another page prior to them reaching this point.
<?php # add_cart.php
// This page adds beers to the shopping cart.
if (isset($_GET['beer_id'])) { // Check for a beer ID.
$beer_id = $_GET['beer_id'];
// Check if the cart already contains one of these beers;
// If so, increment the quantity:
if (isset($_SESSION['cart'][$beer_id])) {
echo '<p> same beer </p>';
$_SESSION['cart'][$beer_id]['quantity']++; // Add another.
// Display a message:
echo '<p> This brew was already in your cart so we added another to your shopping cart. </p>';
} else { // New product to the cart.
require ('mysqli_connect.php'); // Connect to the database.
$q = "SELECT price FROM beer WHERE beer_id='" . $beer_id . "'";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid beer_ID.
// Fetch the information.
list($price) = mysqli_fetch_array ($r, MYSQLI_NUM);
// Add to the cart:
$_SESSION['cart'] = array('quantity' => 1, 'price' => $price);
echo $_SESSION['cart'][$beer_id][$r];
// Display a message:
echo '<p>' . $beer_id . 'has been added to your shopping cart.<br/>Go to Cart or Keep Shopping</p>';
} else { // Not a valid beer_ID.
echo '<div align="center">This page has been accessed in error!</div>';
}
mysqli_close($dbc);
}
}// End of isset conditional.
else { // No beer_ID.
echo '<div align="center">This page has been accessed in error!</div>';
}
?>
The page below is called from add_cart.php
<?php
# view_cart.php
// Check if the form has been submitted (to update the cart):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Change any quantities:
foreach ($_POST['quantity'] as $k => $v) {
$beer_id = (int) $k;
$qty = (int) $v;
if ( $qty == 0 ) { // Delete.
unset ($_SESSION['cart'][$beer_id]);
} elseif ( $qty > 0 ) { // Change quantity.
$_SESSION['cart'][$beer_id]['quantity'] = $qty;
}
} // End of FOREACH.
} // End of SUBMITTED IF.
// Display the cart if it's not empty...
if (!empty($_SESSION['cart'])) {
// Retrieve information for beers in cart:
require ('mysqli_connect.php'); // Connect to the database.
$q = "SELECT beer_id, name, price FROM beer WHERE beer_id ='".$beer_id."'";
/*foreach ($_SESSION['cart'] as $beer_id => $value) {
$q .= $beer_id . ',';
}*/
$q = substr($q, 0, -1) . ') ORDER BY beer_id ASC';
$r = mysqli_query ($dbc, $q);
// Create a form and a table:
echo '<form action="view_cart.php" method="post">
<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="30%"><b>ID</b></td>
<td align="left" width="30%"><b>Name</b></td>
<td align="right" width="10%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="10%"><b>Total Price</b></td>
</tr>
';
// Print each item...
$total = 0; // Total cost of the order.
while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) {
// Calculate the total and sub-totals.
$subtotal = $_SESSION['cart'][$row['beer_id']]['quantity'] * $_SESSION['cart'][$row['beer_id']]['price'];
$total += $subtotal;
// Print the row:
echo "\t<tr>
<td align=\"left\">{$row['name']}</td>
<td align=\"right\">\${$_SESSION['cart'][$row['beer_id']]['price']}</td>
<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['beer_id']}]\" value=\"{$_SESSION['cart'][$row['beer_id']]['quantity']}\" /></td>
<td align=\"right\">$" . number_format ($subtotal, 2) . "</td>
</tr>\n";
} // End of the WHILE loop.
mysqli_close($dbc); // Close the db connection.
// Print the total, close the table, and the form:
echo '<tr>
<td colspan="4" align="right"><b>Total:</b></td>
<td align="right">$' . number_format ($total, 2) . '</td>
</tr>
</table>
<div align="center"><input type="submit" name="submit" value="Update My Cart" /></div>
</form><p align="center">Enter a quantity of 0 to remove an item.
<br /><br />Checkout</p>';
} else {
echo '<form action="view_cart.php" method="post">
<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="10%"><b>ID</b></td>
<td align="left" width="30%"><b>Name</b></td>
<td align="right" width="30%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="10%"><b>Total Price</b></td>
</tr></table>
';
echo '<p>Your cart is currently empty.</p>';
}
?>

PHP - How can I insert multiple items from a shopping cart into the database?

I'd like to apologize in advance if this question has been asked before. I've been surfing this website for a couple of hours trying to find the answer I'm looking for but no luck.
Here's my problem:
I've created this online shopping cart based on a tutorial from a book by Larry Ullman (PHP and MySQL for Dynamic Websites Edition 1). Everything worked well until i realized that the writer stopped at the checkout.php
I need help coding the checkout page. My biggest problem is inserting multiple products from the shopping cart into the database as individual rows.
Can anyone help?
Thanks.
Here's what i have so far:
<?php
session_start();
if (is_numeric ($_GET['pid'])) {
$pid = $_GET['pid'];
if (isset ($_SESSION['cart'][$pid])) {
$qty = $_SESSION['cart'][$pid] + 1;
} else {
$qty = 1;
}
$_SESSION['cart'][$pid] = $qty;
echo '<p>The item has been added to your shopping cart.</p>';
}
if (isset ($_POST['submit'])) {
foreach ($_POST['qty'] as $key => $value) {
if ( ($value == 0) AND (is_numeric ($value)) ) {
unset ($_SESSION['cart'][$key]);
} elseif ( is_numeric ($value) AND ($value > 0) ) {
$_SESSION['cart'][$key] = $value;
}
}
}
$empty = TRUE;
if (isset ($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $key => $value) {
if (isset($value)) {
$empty = FALSE;
}
}
}
if (!$empty) {
include("config.php");
$query = 'SELECT * FROM buds_customer, buds_product WHERE buds_customer.customer_id = buds_product.customer_id AND buds_product.print_id IN (';
foreach ($_SESSION['cart'] as $key => $value) {
$query .= $key . ',';
}
$query = substr ($query, 0, -1) . ') ORDER BY buds_customer.last ASC';
$result = mysql_query ($query);
echo '<table border="0" width="90%" cellspacing="3" cellpadding="3" align="center">
<tr>
<td align="left" width="30%"><b>Seller</b></td>
<td align="left" width="30%"><b>Product</b></td>
<td align="right" width="10%"><b>Price</b></td>
<td align="center" width="10%"><b>Qty</b></td>
<td align="right" width="10%"><b>Total Price</b></td>
</tr>
<form action="view_cart.php" method="post">
';
$total = 0; // Total cost of the order.
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
$subtotal = $_SESSION['cart'][$row['print_id']] * $row['price'];
$total += $subtotal;
echo " <tr>
<td align=\"left\"><input type=\"text\" name=\"seller\" value=\" {$row['first']} {$row['last']}\"></td>
<td align=\"left\"><input type=\"text\" name=\"product\" value=\" {$row['product']}\"></td>
<td align=\"right\"><input type=\"text\" name=\"price\" value=\" {$row['price']}\"></td>
<td align=\"center\"><input type=\"text\" size=\"3\" name=\"qty[{$row['print_id']}]\" value=\"{$_SESSION['cart'][$row['print_id']]}\" /></td>
<td align=\"right\"><input type=\"text\" name=\"subtotal\" value=\"" . number_format ($subtotal, 2) . "\"></td>
</tr>\n";
}
echo ' <tr>
<td colspan="4" align="right"><b>Total:<b></td>
<td align="right"><input type="text" size="3" name="total" value="' . number_format ($total, 2) . '"></td>
</tr>
</table><div align="center"><input type="submit" name="submit" value="Update My Cart" /></form><br /><br /><center>Checkout</center></div>
';
} else {
echo mysql_error();
}
?>
Your example doesn't show any insert statements at all... You should lookup and learn INSERT INTO (http://www.w3schools.com/php/php_mysql_insert.asp). Then you will end up have a foreach loop... the basic code will end up looking something like this:
foreach ($items as $item) {
$sql = 'INSERT INTO `order_history` (`productid`, `productqty`)'
. ' VALUES ($item['product_id'], $item['product_qty']);
mysql_query($sql);
}
Of course I'm leaving out error checking and all kinds of extra fields you will want to populate... but you get the idea. Good luck!

SQL database interaction

I am making a database, which will interact with a SQL table.
What I have achieved so far:
Add rows to the table.
Delete rows from the table.
Search rows from the table.
Paginate the results.
What I need to achieve:
A log in prompt when a guest tries to
access the page.
In fact, I have successfully installed a log in script for it, but it seems to not work properly, here is the error:
Fatal error: Allowed memory size of
25165824 bytes exhausted (tried to
allocate 77824 bytes) in
/home/vol3/byethost12.com/b12_3598660/htdocs/coordbase/database.php on line 238
Now that I do not have permission to allow more memory from my host, I would need a way around this.
I have already tried separating the file into multiple pages, but it seems that it still tried to allocate the same amount of bytes.
Here is the file:
<?php
require_once('db.php'); // for database details
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require('../include/session.php');
if (!$session->isMember())
{
header("../resources.php");
}
else
{
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
$connect = mysql_connect($host,$username,$password) or die('<p class="error">Unable to connect to the database server at this time.</p>');
mysql_select_db($database,$connect) or die('<p class="error">Unable to connect to the database at this time.</p>');
require('../include/header.php');//Page Header
if($_GET['cmd'] == "delete")
{
echo "<center><h1>Delete</h1></center>";
if(isset($_POST['delete'])) {
$time = date("Y-m-d H:i:s");
$queryc = "DELETE FROM coords WHERE id=".$_GET['id'].";";
$resultc = mysql_unbuffered_query("$queryc") or die("Could not delete the selected base from the database at this time, please try again later.");
$sqls = "INSERT INTO reports SET ip='$ipaddress', date='$time';";
//run the query. if it fails, display error
$report = mysql_unbuffered_query("$sqls") or die("Could not add report to the database, but the base has been deleted successfully.");
echo "<center>The selected base has been deleted from the database successfully!<br>
<a href=http://www.teamdelta.byethost12.com/coordbase/database.php>Back to Main</a><br><br>
<font color=\"red\"><b>YOUR IP HAS BEEN LOGGED. ABUSE OF THIS SYSTEM WILL RESULT IN AN IP BAN!</b></font></center>";
}
else
{
$queryd = "SELECT * FROM coords WHERE id=".$_GET['id'].";";
$resultf = mysql_unbuffered_query("$queryd") or die('<p class="error">There was an unexpected error grabbing the base from the database.</p>');
?>
<center>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
</tr>
<?php
while ($rowa = mysql_fetch_array($resultf)) {
$id = stripslashes($rowa['id']);
$tag = stripslashes($rowa['tag']);
$guild = stripslashes($rowa['guild']);
$name = stripslashes($rowa['name']);
$base = stripslashes($rowa['base']);
$location = stripslashes($rowa['location']);
$comment = stripslashes($rowa['comment']);
$id = stripslashes($rowa['id']);
$econ = stripslashes($rowa['econ']);
$maxecon = stripslashes($rowa['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td></center></tr>');
}
?>
</table>
</table>
<b>Are you sure you wish to delete the selected base?</b>
<br>
<input type="button" value="Cancel" id="button1" name="button1"onclick="window.location.href='database.php';">
<form action="<?php $self ?>" name="deletefrm" method="post" align="right" valign="bottom" onsubmit="return validate();">
Confirm Delete<input type=checkbox name="confirm"><input type="submit" name="delete" value="Delete" />
</form>
</center>
<br>
<center><font color="red"><b>YOUR IP WILL BE LOGGED. ABUSE OF THIS SYSTEM WILL RESULT IN AN IP BAN!</b></font></center>
<?php
}
}
else
{
if(isset($_POST['add'])) {
?>
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Info«</font></b></center>
</td>
</tr>
<tr><!--info content-->
<td style="background: #222222;">
<?php
//fetch data
$data = strip_tags(mysql_real_escape_string($_POST['list']));
$comment = strip_tags(mysql_real_escape_string($_POST['comment']));
$data_lines = explode( "\\r\\n", $data );
$comment_lines = explode("\\r\\n", $comment);
for($i=0;$i<count($data_lines);$i++)
{
$data_fields = explode( ",", $data_lines[$i]);
$time = time();
$queryb = "INSERT INTO coords SET
tag='{$data_fields[0]}',
guild='{$data_fields[1]}',
name='{$data_fields[2]}',
base='{$data_fields[3]}',
econ='{$data_fields[5]}',
maxecon='{$data_fields[6]}',
location='{$data_fields[4]}',
comment='{$comment_lines[$i]}',
ipaddress='$ipaddress' ,
date='$time';";
// if it succeeds, display message
if (mysql_unbuffered_query($queryb))
{
echo('<p class="success">Successful posting of ['.$data_fields[3].']!</p>');
}
else
{
echo('<p class="error">Error could not post ['.$data_fields[3].'] to database!</p>');
}
}//end for loop
}//end if $_POST['add'] statement
?>
<?php
if (isset($_GET['cmd']) == "add"){
?>
<!--start inputbox-->
<center><table width="100%">
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Add«</font></b></center>
</td>
</tr>
<tr>
<td style="background: #222222;"><!-- at the bottom of the page, we display our comment form -->
<form action="<?php $self ?>" method="post" onsubmit="return valid(this)">
<table width="100%" border ="0" valign="top">
<tr>
<td>
List:
</td>
<td align="left">
<textarea name="list" rows="10" cols="70"></textarea>
</td>
<td valign="top">
<font color="red"><b>[Post list arranged like so!]</b></font><br>
<br>
E.G:<br>
<br>
(tag),(guild),(player,(base),(coordinates),(econ),(maxecon)<br>
~TD~,~Team Delta~,DarkLink,Base1,D03:56:21:11,101,101<br>
FARM,Guild896,player 5,Base #3,D69:62:89:10,98,135<br>
</td>
</tr>
</tr>
<td>
Comment:
</td>
<td>
<textarea name="comment" rows="10" cols="70"></textarea>
</td>
<td>
<font color="red"><b>[Post comments on a new line for each base!]</b></font><br>
E.G "PS 10/10 PR 10/10"<br>
"PR 5/5 DT 10/10"
</td>
<td>
<td>
</td>
<td valign="bottom" align="right">
<p>
<input type="submit" name="add" value="Add" />
</p>
</td>
</tr>
</table>
</form>
Back to Main
</td>
</tr>
</table></center>
<!--end input box-->
<?php
}
else
{
if (isset($_GET['search']) == "do"){
$title = "<center><h1>Results</h1>";
$search = stripslashes($_GET['searchterm']);
$asearch = trim($search);
$bsearch = strip_tags($asearch);
$csearch = mysql_real_escape_string($bsearch);
$types = "types of search";
switch ($_GET['type']){
case 'name':
$types = "name";
break;
case 'tag':
$types = "tag";
break;
case 'guild':
$types = "guild";
break;
default:
$types = "";
echo "<center><b>Please select a search type before continuing! You are being redirected, please wait.<br>
Click here, if you do not wish to wait.</b></center>";
header("Refresh: 5; url=http://www.teamdelta.byethost12.com/coordbase/database.php");
exit;
break;
}
$querya = "SELECT * FROM coords WHERE `{$types}` LIKE '%{$csearch}%' ORDER BY `{$types}`;";
$result = mysql_unbuffered_query("$querya") or die("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$querya}");
if (mysql_num_rows($result) < 1) {
echo $title;
echo "<b><center>We are sorry to announce that the search term provided: \"{$search}\", yielded no results. <br>"
."<hr>"
."New Search</center></b>";
exit;
}else {
echo $title;
?>
<b>for "<?php echo $search;?>".</b>
<hr>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
<td ><b>Delete</b></td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
$id = stripslashes($row['id']);
$tag = stripslashes($row['tag']);
$guild = stripslashes($row['guild']);
$name = stripslashes($row['name']);
$base = stripslashes($row['base']);
$location = stripslashes($row['location']);
$comment = stripslashes($row['comment']);
$id = stripslashes($row['id']);
$econ = stripslashes($row['econ']);
$maxecon = stripslashes($row['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td><td><a href=database.php?id='.$id.'&cmd=delete>Delete</a></td></center></tr>');
}
echo "New Search";
?>
</table>
</table>
<?php
}
}
else{
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM coords";
$result = mysql_unbuffered_query($sql, $connect) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
?>
</center>
<!--start inputbox-->
<center>
<table width="83%">
<tr>
<td style="background: url(http://www.teamdelta.byethost12.com/barbg.jpg) repeat-x top;">
<center><b><font color="#F3EC84">»Search«</font></b></center>
</td>
</tr>
<tr>
<td style="background: #222222;"><!-- at the bottom of the page, we display our comment form -->
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm" onsubmit="return valid(this)">
<table border ="0" width="100%">
<tr>
<td><center>
Search For: <input type="text" name="searchterm">
Player <input type="radio" name="type" value="name" checked> |
Guild Tag <input type="radio" name="type" value="tag"> |
Guild Name <input type="radio" name="type" value="guild">
<input type="hidden" name="search" value="do">
<input type="submit" value="Search">
Add new bases
</tr>
</center>
</td>
</tr>
</form>
</td>
</tr>
</table>
</center>
<!--end input box-->
<hr>
<center>
<table>
<table width="83%" border="1">
<tr>
<td ><b>Tag</b></td>
<td ><b>Guild</b></td>
<td ><b>Player</b></td>
<td ><b>Base</b></td>
<td ><b>Location</b></td>
<td ><b>Econ</b></td>
<td ><b>Comments</b></td>
<td ><b>Delete</b></td>
</tr>
<?php
$query = "SELECT * FROM coords ORDER BY `tag` ASC LIMIT $offset, $rowsperpage;";
$result = mysql_unbuffered_query("$query") or die('<p class="error">There was an unexpected error grabbing routes from the database.</p>');
// while we still have rows from the db, display them
while ($row = mysql_fetch_array($result)) {
$id = stripslashes($row['id']);
$tag = stripslashes($row['tag']);
$guild = stripslashes($row['guild']);
$name = stripslashes($row['name']);
$base = stripslashes($row['base']);
$location = stripslashes($row['location']);
$comment = stripslashes($row['comment']);
$id = stripslashes($row['id']);
$econ = stripslashes($row['econ']);
$maxecon = stripslashes($row['maxecon']);
echo('<tr><center><td>['.$tag.']</td><td>'.$guild.'</td><td>'.$name.'</td><td>'.$base.'</td><td>'.$location.'</td><td>'.$econ.'/'.$maxecon.'</td><td>'.$comment.'</td><td><a href=database.php?id='.$id.'&cmd=delete>Delete</a></td></center></tr>');
}
?>
</table>
</table>
<?php
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
}//end else of search
}//end else of add
}//end else of delete
?>
</center>
<?php
require('../include/footer.php');//Page footer
}
?>
This would be around line 238:
<?php
//fetch data
$data = strip_tags(mysql_real_escape_string($_POST['list']));
$comment = strip_tags(mysql_real_escape_string($_POST['comment']));
$data_lines = explode( "\\r\\n", $data );
$comment_lines = explode("\\r\\n", $comment);
for($i=0;$i<count($data_lines);$i++)
{
$data_fields = explode( ",", $data_lines[$i]);
$time = time();
$queryb = "INSERT INTO coords SET
tag='{$data_fields[0]}',
guild='{$data_fields[1]}',
name='{$data_fields[2]}',
base='{$data_fields[3]}',
econ='{$data_fields[5]}',
maxecon='{$data_fields[6]}',
location='{$data_fields[4]}',
comment='{$comment_lines[$i]}',
ipaddress='$ipaddress' ,
date='$time';";
// if it succeeds, display message
if (mysql_unbuffered_query($queryb))
{
echo('<p class="success">Successful posting of ['.$data_fields[3].']!</p>');
}
else
{
echo('<p class="error">Error could not post ['.$data_fields[3].'] to database!</p>');
}
}//end for loop
}//end if $_POST['add'] statement
?>
I have noticed that the memory exceeds the limit when I include session.php to my file.
The problem is that I need that file for my log in prompt to work.
Check for recursions, this code cannot possibly exhaust memory. Try adding echo's around the code.

Categories