I've been new to programming and I been working with phpmyadmin on localhost. I am making a simple table on a webpage to display data. The problem is that everytime I load the page it only displays the table and not table will load up. Here is my code:
<?php
require('../model/database.php');
require('../model/product_db.php');
$products = get_products();
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'under_construction';
}
// Display the product list
include('view-productList.php');
?>
This is the view-productList.php:
<?php include '../view/header.php'; ?>
<div id="main">
<h1>Product List</h1>
<div id="content">
<!-- display a table of products -->
<h2><?php echo $name; ?></h2>
<table>
<tr>
<th>Code</th>
<th>Name</th>
<th class="right">Version</th>
<th> </th>
</tr>
<?php foreach ($products as $product) : ?>
<tr>
<td><?php echo $product['productCode']; ?></td>
<td><?php echo $product['name']; ?></td>
<td class="right"><?php echo $product['version']; ?></td>
<td><form action="." method="post">
<input type="hidden" name="action"
value="delete_product" />
<input type="hidden" name="product_id"
value="<?php echo $product['productID']; ?>" />
<input type="hidden" name="category_id"
value="<?php echo $product['categoryID']; ?>" />
<input type="submit" value="Delete" />
</form></td>
</tr>
<?php endforeach; ?>
</table>
<p>Add Product</p>
</div>
</div>
<?php include '../view/footer.php'; ?>
Query Page:
<?php
function get_products() {
global $db;
$query = 'SELECT * FROM products
ORDER BY productID';
$products = $db->query($query);
return $products;
}
function get_products_by_category($category_id) {
global $db;
$query = "SELECT * FROM products
WHERE products.categoryID = '$category_id'
ORDER BY productID";
$products = $db->query($query);
return $products;
}
function get_product($product_id) {
global $db;
$query = "SELECT * FROM products
WHERE productID = '$product_id'";
$product = $db->query($query);
$product = $product->fetch();
return $product;
}
function delete_product($product_id) {
global $db;
$query = "DELETE FROM products
WHERE productID = '$product_id'";
$db->exec($query);
}
product_db.php should not be commented out for one - assuming that is the file that holds the "Query Page:" contents.
$products = get_products();
should come immediately after the include.
and your for loop needs the fetch result and not just the product resource:
<?php foreach ($products->fetch() as $product) : ?>
assuming fetch() is relevant to this type of resource since we can't see your db class.
Related
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...";
}
}
}
?>
Hi i have this worpdress project plugin ive created. The data is successfully rendered in the wp-admin from the database. Now my problem is it seems my sql delete query is not working which is my sql delete code seems to be okay. here is my code below
add_action('admin_menu', 'zipcode_menu');
function zipcode_menu(){
add_menu_page( 'Zipcode Page', 'Zipcode', 'manage_options', 'zipcode', 'zipcode' );
}
function zipcode() {
// Now display the settings editing screen
echo '<div class="wrap">';
// header
echo "<h2>" . __( 'Zipcode', 'zip' ) . "</h2>";
// settings form
if(isset($_POST['Submit'])){
global $wpdb;
$zipcode = $_POST['zipcode'];
$wpdb->query("INSERT INTO zipcode(zipcode)VALUES('$zipcode')" );
}
?>
<form method="post" action="">
<table class="form-table">
<tr valign="top">
<td><input type="text" name="zipcode" placeholder="Zipcode: " value=""/></td>
</tr>
</table>
<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Add Zipcode') ?>" />
</p>
</form>
</div>
<br>
<br>
<?php
global $wpdb;
$sql = "SELECT id, zipcode FROM zipcode;";
$results = $wpdb->get_results($sql);
?>
<script type="text/javascript">
jQuery.noConflict();
function goDelete($id){
var x = confirm('Are you sure you want to delete this?');
if(x){
jQuery.post("/wp-content/themes/doozo/lib/script.php", { id:$id }, function(data){
});
}else{
return false;
}
}
</script>
<table width="600px">
<tr>
<th>
Zipcode
</th>
<th>
Options
</th>
</tr>
<?php foreach($results as $r): ?>
<tr class="zipcode-<?php echo $r->id; ?>">
<th>
<?php echo $r->zipcode; ?>
</th>
<th>
<a onclick="goDelete('<?php echo $r->id; ?>')" href="#">Delete</a>
</th>
</tr>
<?php endforeach; ?>
</table>
<?php
}
Now my script.php code to delete the data from the table
global $wpdb;
$id = $_POST['id'];
echo $id;
// sql to delete a record
$sql = "DELETE FROM zipcode where id=$id";
echo $sql; exit;
Can someone try to help me figured this thing out? It seems my delete query is not working. Any help is muchly appreciated. TIA
Try this:
<?php
global $wpdb;
$id = $_POST['id'];
echo $id;
// sql to delete a record
//$sql = 'DELETE FROM zipcode WHERE id="'. $id .'"';
$wpdb->delete( 'zipcode', array( 'id' => $id ) );
?>
When I submit my category search form, I want it to run the php code in the DisplayMealsCont.php and then go back to the main.php with the updated session variables. But when I try to put in a Header("Location: ../View/Main.php"); in the DisplayMealsCont.php it gets stuck in a redirect loop.
main.php
<?php
require_once("../Controller/DisplayMealsCont.php");
session_start();
$category = "All";
if(isset($_SESSION['table'])){
$table = $_SESSION['table'];
}
if(isset($_SESSION['Category'])){
$category = $_SESSION['Category'];
if($category == "All"){
$category = " ";
}
}
?>
<?php
if (is_array($table)) {
foreach($table as $item) {
?>
<td align="centre"> <?= $item['Meal_Name'] ?> </td>
<td align="centre"> <?= $item['Description'] ?> </td>
<td align="centre"> <?= $item['Image'] ?> </td>
<td align="centre"> <?= $item['Category'] ?> </td>
<td align="centre"> <?= $item['Quantity'] ?> </td>
<td align="centre"> £ <?= $item['Price'] ?> </td>
<tr>
<?php
}
}
?>
</table>
<form method="post" action="../Controller/DisplayMealsCont.php">
Category: <br />
<select name="Category">
<option value="All">All</option>
<option value="Main">Main</option>
<option value="Drink">Drinks</option>
</select> <br />
<input type="submit" name="categorysubmit" value="Search" />
</form>
DisplayMealModel.php
<?php
require_once("../Model/config.php");
class DisplayMeals
{
public $dbConnection;
public function __construct(){
$db= new database();
$connect=$db->getdatabase();
$this->dbConnection = $connect;
}
public function MainMeals($category){
$_SESSION['test'] = $category;
$stmt = $this->dbConnection->prepare("SELECT * from meal WHERE Category LIKE '$category%'");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
DisplayMealCont.php
<?php
require("../Model/DisplayMealModel.php");
$newMeal = new DisplayMeals();
if(!isset($category)){
$category = "main";
}
if(isset($_SESSION['Category'])){
$category = $_SESSION['Category'];
}
$table = $newMeal-> MainMeals($category);
$_SESSION['table'] = $table;
?>
I can't see why a header() in there causes a redirection loop, but have you tried adding a die(); after header()?
It's a good practice, and in case it works it may shed light into what is causing the issue. Other than that, it would help if you posted the code with the looping header in it so we can see.
I am trying to create a shopping cart in PHP. I understand how to to use sessions with hard coded products but I am having a hard time trying to retrieve products from a SQL database.
This is what I have so far.
CART.php:
function add_item($key, $quantity) {
global $products;
if ($quantity < 1) return;
// If item already exists in cart, update quantity
if (isset($_SESSION['cart'][$key])) {
$quantity += $_SESSION['cart'][$key]['qty'];
update_item($key, $quantity);
return;
}
// Add item
$cost = $products[$key]['cost'];
$total = $cost * $quantity;
$item = array(
'name' => $products[$key]['name'],
'cost' => $cost,
'qty' => $quantity,
'total' => $total
);
$_SESSION['cart'][$key] = $item;
}
CART_VIEW.php
<h1>Your Cart</h1>
<?php if (empty($_SESSION['cart']) || count($_SESSION['cart']) == 0) : ?>
<p>There are no items in your cart.</p>
<?php else: ?>
<form action="." method="post">
<input type="hidden" name="action" value="update">
<table>
<tr id="cart_header">
<th class="left">Item</th>
<th class="right">Item Cost</th>
<th class="right">Quantity</th>
<th class="right">Item Total</th>
</tr>
<?php foreach( $_SESSION['cart'] as $key => $item ) :
$cost = number_format($item['cost'], 2);
$total = number_format($item['total'], 2);
?>
<tr>
<td>
<?php echo $item['name']; ?>
</td>
<td class="right">
$<?php echo $cost; ?>
</td>
<td class="right">
<input type="text" class="cart_qty"
name="newqty[<?php echo $key; ?>]"
value="<?php echo $item['qty']; ?>">
</td>
<td class="right">
$<?php echo $total; ?>
</td>
</tr>
<?php endforeach; ?>
<tr id="cart_footer">
<td colspan="3"><b>Subtotal</b></td>
<td>$<?php echo get_subtotal(); ?></td>
</tr>
<tr>
<td colspan="4" class="right">
<input type="submit" value="Update Cart">
</td>
ADD_ITEM.php
<h1>Add Item</h1>
<form action="../cart/index.php" method="post">
<input type="hidden" name="action" value="add">
<label>Name:</label>
<section>
<h1><?php echo $name; ?></h1>
<div id="left_column">
<p>
</p>
<select name="productkey">
<?php foreach($products as $key => $product) :
$cost = number_format($product['cost'], 2);
$name = $product['name'];
$item = $name . ' ($' . $cost . ')';
?>
<option value="<?php echo $key; ?>">
<?php echo $item; ?>
</option>
<?php endforeach; ?>
</select><br>
<label>Quantity:</label>
<select name="itemqty">
<?php for($i = 1; $i <= 10; $i++) : ?>
<option value="<?php echo $i; ?>">
<?php echo $i; ?>
</option>
<?php endfor; ?>
</select><br>
<label> </label>
<input type="submit" value="Add Item">
</form>
INDEX.php
<?php
$lifetime = 60 * 60 * 24 * 365 * 4; // 3 years in seconds
session_set_cookie_params($lifetime, '/');
session_start();
// Create a cart array if needed
if (empty($_SESSION['cart'])) { $_SESSION['cart'] = array(); }
// Create a table of products
$products = array(); //hard coded products <------------
$products['MMS-1754'] = array('name' => 'PC', 'cost' => '549.50');
// Include cart functions
require_once('cart.php');
// Get the action to perform
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'show_add_item';
}
}
// Add or update cart as needed
switch($action) {
case 'add':
$product_key = filter_input(INPUT_POST, 'productkey');
$item_qty = filter_input(INPUT_POST, 'itemqty');
add_item($product_key, $item_qty);
include('cart_view.php');
break;
case 'show_cart':
include('cart_view.php');
break;
case 'show_add_item':
include('add_item_view.php');
break;
case 'end_session':
// Clear session data from memory
$_SESSION = array();
// Clean up session ID
session_destroy(); ...
products_db
<?php
function get_products() {
global $db;
$query = 'SELECT productID, categoryID, productName,description,price,imageFile
FROM products
ORDER BY productID' ;
$statement = $db->prepare($query);
$statement->execute();
$products = $statement->fetchAll();
$statement->closeCursor();
return $products;
}
function get_products_by_name($product_id) {
global $db;
$query = 'SELECT * FROM products
WHERE products.productName = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(":product_id", $product_id);
$statement->execute();
$product_name = $statement->fetchAll();
$statement->closeCursor();
return $product_name;
}
function get_products_by_category($category_id) {
global $db;
$query = 'SELECT * FROM products
WHERE products.categoryID = :category_id
ORDER BY productID';
$statement = $db->prepare($query);
$statement->bindValue(":category_id", $category_id);
$statement->execute();
$product = $statement->fetchAll();
$statement->closeCursor();
return $product;
}
function get_product($product_id) {
global $db;
$query = 'SELECT * FROM products
WHERE productID = :product_id';
$statement = $db->prepare($query);
$statement->bindValue(":product_id", $product_id);
$statement->execute();
$product = $statement->fetch();
$statement->closeCursor();
return $product;
}
Is there a different function I need. I tried with a product id and using a the GET array but the sessions would print null (using var-dump to check).
I have a page that contains an ordering form, on this form it lists the vendor information and then each of the products for the vendor underneath and in front of the product is an input field that allows the user to input the quantity of each product that they want.
Upon submitting the information goes to a confirmation page where I need to be able to show the order information. On the form on the order page, I have a hidden field that contains the vendor id. and the vendor id is put once for each vendor. What I need to be able to do is not only echo out the quantity but also echo out the vendor id specific for each order. My code is below. The first block is the order page and then the block below that will be the confirm page.
As it stands right now underneath every quantity it displays all the vendor ids as opposed to just the one I need.
<?php defined('C5_EXECUTE') or die("Access Denied.");?>
<div class="ccm-ui">
<?php
$db= Loader::db(); //This loads the database helper.
Loader::model('user'); //This loads the user Model.
$user = new User();
$userInfo = UserInfo::getByID($user->getUserID()); //This gets the user info for the current user.
$userCostCenter = $userInfo->getAttribute('cost_center'); //This sets a variable equal to the attribute Cost Center for the current user.
//The if statement below checks if the user is an admin and then displays the info accordingly.
if ($userCostCenter === "Admin") {
?>
<form name="SelectCostCenter" action="/adminorder" method="POST">
<select name="CostCenter">
<option value="unitedilluminating">United Illumination</option>
<option value="clp">CL&P</option>
</select>
<input type="submit" value="Continue">
<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
<?php
} elseif ($userCostCenter === "United Illuminating") {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php
$query = 'SELECT * FROM Vendors WHERE costCenterID = 1';
$productQuery = 'SELECT * FROM Products WHERE costCenterID = 1';
$results = $db->getAll($query);
$productResults = $db->getAll($productQuery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category']; ?></td>
<td><?php echo $vendor['Vendor']; ?></td>
<td><?php echo $vendor['Address']; ?></td>
</tr>
<?php foreach ($productResults as $product) { ?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[]" size="1" /><?php echo $product['Product'];?></span></td>
</tr>
<?php } ?>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
else {
?>
<form name="OrderForm" action="/confirm" method="POST">
<?php $query = 'SELECT * FROM Vendors Where costCenterID = 2';
$productquery = 'SELECT * FROM Products WHERE costCenterID = 2';
$results = $db->getAll($query);
$productresults = $db->getAll($productquery);?>
<table class="table">
<thead>
<tr>
<th>Quantity/Product</th>
<th>Category</th>
<th>Vendor</th>
<th>Address</th>
</tr>
<?php
foreach ($results as $vendor) {
?>
<tr class="category">
<td></td>
<td><?php echo $vendor['Category'];?></td>
<td><?php echo $vendor['Vendor'];?> </td>
<td><?php echo $vendor['Address'];?></td>
</tr>
<?php
foreach ($productresults as $product){
?>
<tr class="product">
<td colspan="4"><span class="name"><input type="text" name="quantities[<?php echo $vendor['vendorID']; ?>]" size="1" /><?php echo $product['Product'];?></span></td>
<td><input type="hidden" name="vendor[]" value="<?php echo $vendor['vendorID']; ?>"/></td>
</tr>
<?php
}
?>
<?php
}?>
</table>
<input type="submit" value="Checkout"<button style="float:right;" type="button" class="btn btn-primary"></button>
</form>
</div><?php
}
?>
This is the confirm page below.
<?php defined('C5_EXECUTE') or die("Access Denied.");
$db= Loader::db();
$quantity = $_POST['quantities'];
$vendor = $_POST['vendor'];
$minimumorder = 25;
foreach($quantity as $num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
foreach($vendor as $vendors){
echo "$vendors";
echo "</br>";
}
}
}
?>
I appreciate any help anyone can give. This has had me stumped for a few days actually.
you might want to rearrange your array, and do something like:
$i = 0;
foreach ($productresults as $product) {
echo '<input name="product['.$i.'][quantity]" />';
echo '<input name="product['.$i.'][vendor_id]" value="'.$vendor['vendorID'].'" type="hidden" />';
++$i;
}
The resulting array in $_POST would have the quantities & their vendor separated into their own arrays.
In your code $vendor['vendorID'] seems the key of your $_POST['quantities'] so in your confirm page you could use:
foreach($quantity as $vendorid=>$num){
if ($num >= $minimumorder){
echo "$num";
echo "</br>";
echo "$vendorid";
}
}