I have a products table where I have products being listed into. I want to create a peice of code that will show the same style but different price, name, description, picture for each product. I have create a peice of code that sort of does this. My code displays only the first in the row. I need to list all of them. My code is :
function grabProducts($con) {
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="col-md-12" id="please_wait">
<div class="panel panel-warning">
<div class="panel-heading">
<h3 class="panel-title"><i>Loading, Please Wait...</i></h3>
</div>
<div class="panel-body">
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#please_wait').fadeOut(7000);
$('#content_purchase').hide(0).delay(5000).fadeIn("slow");
});
</script>
<?php
$users = $this->grabUserInfos($con);
foreach ($users as $user) {
$username = $user[1];
$email = $user[3];
}
$site_config = new site_config();
$member_config = new member_config();
$result = mysqli_query($con, "SELECT * FROM products");
$count = mysqli_num_rows($result);
// See if there are any products in the database
if ($count > 0) {
// While loop for each product element
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$picture = $row['picture_location'];
$price = $row['price'];
$stock_monitering = $row['stock_monitering'];
$stock = $row['stock'];
$new_stock = $stock - 1;
$url_path = 'http' . (empty($_SERVER['HTTPS']) ? '' : 's') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url_path_naked = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH).'/pizza/products.php';
$getValidatedCheck_ = mysqli_query($con, "SELECT txn_id, hasValidated, item_name, amount, currency, payment_date FROM payment_logs WHERE userId = '$username' ORDER BY id DESC LIMIT 1");
$count_success_payment = mysqli_num_rows($getValidatedCheck_);
// While loop for our successful payment_logs for each user
while ($row = mysqli_fetch_array($getValidatedCheck_)) {
$txn_id = $row['txn_id'];
$validated_check = $row['hasValidated'];
$item_name = $row['item_name'];
$item_price = $row['amount'];
$item_currency = $row['currency'];
$payment_date = $row['payment_date'];
$now = strtotime("-10 minutes");
// If there is not enough stock, show out of stock
if($stock <= 0) {
$display = 'out_of_stock';
} else if($stock > 0 && $now > strtotime($payment_date)) {
$display = 'show_products';
}
// If there are no transactions for that user show the products like normal
if($count_success_payment == 0) {
// If they've not already seen the success message, show them it now and update their hasValidated from 0 to 1 so they don't see it again
if ($validated_check == '0') {
// If stock monitering is on, update our stock to 1 less than we had before the purchase
if($stock_monitering == '1') {
mysqli_query($con, "UPDATE products SET stock = '$new_stock' WHERE name = '$name'");
}
$display = 'show_success';
}
}
}
switch($display) {
case "show_products":
?>
<div class="col-md-3" id="content_purchase" style="display: none;">
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Price: <i>$<?php echo $price; ?></i>
<div class="fRight" style="float: right;"><i><?php echo $name; ?></i> Stock
(<?php echo $stock; ?>)
</div>
</h3>
</div>
<center>
<div class="panel-body">
<img src="<?php echo $picture; ?>"
style="width: 85%; height: 100px; margin: 15px 0px 15px 0px; border-radius: 5px; border: 2px solid #ED4949;">
<form name="paypal_form" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business"
value="<?php $site_config->grabSiteSettings($con, 'paypal_address'); ?>">
<input type="hidden" name="item_name" value="<?php echo $name; ?>">
<input type="hidden" name="item_number" value="<?php echo $id; ?>">
<input type="hidden" name="amount" value="<?php echo $price; ?>">
<input type="hidden" name="quantity" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="custom" value="username=<? echo $username; ?>&status=<? echo $checkout_status; ?>&product=<? echo $name; ?>">
<input type="hidden" name="notify_url" value="https://benzaofficial.com/pizza/includes/checkout.php">
<input type="hidden" name="return"
value="<?php $site_config->grabSiteSettings($con, 'site_url'); ?>/pizza/products.php?status=complete">
<input type="hidden" name="cancel_return"
value="<?php $site_config->grabSiteSettings($con, 'site_url'); ?>/pizza/products.php?status=canceled">
<button type="submit" class="btn btn-danger"
style="vertical-align : bottom; margin-bottom: 15px; display: block; width: 85%;">
<i class="fa fa-paypal"></i>aypal
</button>
<form>
</div>
</center>
</div>
</div>
<?php
break;
case "show_success":
?>
<div class="col-md-12" id="content_purchase" style="display: none;">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title"><i>PAYMENT SUCCESS!</i></h3>
</div>
<div class="panel-body">
<p>You've successfully purchased <i><?php echo $item_name; ?></i> for <i><?php echo $item_price; ?> <i><?php echo $item_currency; ?></i></i> We have emailed you your receipt to <?php echo $email; ?>. You can click here to download your purchased files.<br>Click here to purchase again.</p>
</div>
</div>
</div>
<?php
mysqli_query($con, "UPDATE payment_logs SET hasValidated = '1' WHERE userId = '$username' ORDER BY id DESC LIMIT 1");
break;
case "no_products":
?>
<div class="col-md-12" id="content_purchase" style="display: none;">
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title"><i>Currently No Products For Sale</i></h3>
</div>
<div class="panel-body">
<p>There are currently no products up for sale.</p>
</div>
</div>
</div>
<?php
break;
case "out_of_stock":
?>
<div class="col-md-3" id="content_purchase" style="display: none;">
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Price: <i>$<?php echo $price; ?></i>
<div class="fRight" style="float: right;"><i><?php echo $name; ?></i> Stock
(<?php echo $stock; ?>)
</div>
</h3>
</div>
<center>
<div class="panel-body">
<img src="<?php echo $picture; ?>"
style="width: 85%; height: 100px; margin: 15px 0px 15px 0px; border-radius: 5px; border: 2px solid #ED4949;">
<p><i><?php echo $name; ?></i> is currently out of stock. Please come back later and try again.</p>
</div>
</center>
</div>
</div>
<?php
break;
}
}
} else {
$display = 'no_products';
}
}
first you need a function dat select all of your products like this one
function showproducts($conn,$id){
$req="SELECT * FROM products ";
$liste=$conn->query($req);
return $liste->fetchAll();
}
than you should call this function :
$list=$cc->showproducts($cc->conn);
and foreach row you can show all columns
<?php
foreach ($list as $l){ ?>
<tr>
<td><?php echo $l[0] ;?> </td>
<td><?php echo $l[1] ;?> </td>
<td><?php echo $l[2] ;?> </td>
<td><?php echo $l[3] ;?> </td>
<td><?php echo $l[7] ;?> </td>
</tr>
<?php } ?>
Related
I am currently building eCommerce site using CI HMVC method. I completed it for computer design and all back-end. It work perfectly. But my dessign is terrible for mobile so i decided to write jquery mobile code. I almost complete the code in jquery mobile but i got i problem which i cannot solve.
I have the form which is use to add the item into the cart. For this i have add to cart function which has view file add_to_Cart.php whis has actual form. After submitting form goes to store_basket/add_to_basket function. Here i writ code to sore the comming information to store_basket table. Then it redirect the page to another controller cart where i have view file of list of items which is in cart.
when i submit the form it store item in store_basketm table. Then it show the view of cart controller but the url is localhost/shop/store_basket/add_to_basket Which should be localhost/shop/cart. But despite of url localhost/shop/store_basket/add_to_basket it show the contents of localhost/shop/cart
<?php $form_location = base_url().'store_basket/add_to_basket'; ?>
<div id="cart" style="background-color: #ddd; border-spacing: 7px; padding: 7px; color: black;">
<form ajax-date="false" data-url="true" action="<?= $form_location ?>" method="POST">
<table class="table">
<tr>
<td>ID: </td>
<td><?php echo $item_id ?></td>
</tr>
<input type="hidden" name="item_id" value="<?php echo $item_id ?>">
<input type="hidden" name="item_title" value="<?php echo $item_title ?>">
<?php if($num_colour > 0): ?>
<tr>
<td style="padding-top: 20px;">Colour: </td>
<td style="margin-left: 50px;">
<?php
$status = '';
$additional_dd_code = 'name="select-choice-mini" id="select-choice-mini" data-mini="true" data-inline="true"';
echo form_dropdown('item_colour', $colour_options, $submitted_colour, $additional_dd_code);
?>
</td>
</tr>
<?php endif; ?>
<?php if($num_size > 0): ?>
<tr>
<td style="padding-top: 20px;">Size: </td>
<td style="margin-left: 50px;">
<?php
$status = '';
$additional_dd_code = 'name="select-choice-mini" id="select-choice-mini" data-mini="true" data-inline="true" style="background-color: white;"';
echo form_dropdown('item_size', $size_options, $submitted_size, $additional_dd_code);
?>
</td>
</tr>
<?php endif; ?>
<tr>
<td>Price: </td>
<td><?= $item_price ?></td>
</tr>
<input type="hidden" name="price" value="<?= $item_price ?>">
<tr>
<td style="padding-top: 20px;">Qty: </td>
<td>
<input type="number" name="item_qty" value="1" min="1" required>
</td>
</tr>
</table>
<!-- <a rel="external" href=""><input name="submit" value="Submit" class="btn"></a> -->
<button type="submit" name="submit" value="Submit" id="cart-btn" class="ui-shadow ui-btn ui-corner-all" style="margin-top: 20px; width: 75%; margin-left: 30px;"><span class="glyphicon glyphicon-shopping-cart" aria-hidden="true"></span> Add To Basket</button>
<?php echo form_close() ?>
store_basket/add_to_basket
function add_to_basket() {
// var_dump($_POST); exit;
$this->load->module('site_settings');
$this->load->library('session');
$this->load->module('site_security');
$is_mobile = $this->site_settings->is_mobile_device();
$submit = $this->input->post('submit', TRUE);
if($submit == "Submit"){
//library for form validation
$this->load->library('form_validation');
//validation rules
$this->form_validation->set_rules('item_colour', 'Item Color', 'numeric');
$this->form_validation->set_rules('item_size', 'Item Size', 'numeric');
$this->form_validation->set_rules('item_qty', 'quantity', 'required|numeric');
$this->form_validation->set_rules('item_id', 'Item_id', 'required|numeric');
if($this->form_validation->run($this)) {
// echo "Success"; exit;
$data = $this->_fetch_the_data();
$this->_insert($data);
redirect('cart');
} else {
// echo "Fail"; exit;
$refer_url = $_SERVER['HTTP_REFERER'];
$error_msg = validation_errors("<p style='color: red;'>","</p>");
$this->session->set_flashdata('item', $error_msg);
redirect('cart');
}
}
}
cart/index.php
function index() {
// echo "here"; exit;
$this->load->module('site_settings');
$is_mobile = $this->site_settings->is_mobile_device();
$data['flash'] = $this->session->flashdata('item');
$data['view_files'] = "cart";
if($is_mobile==TRUE) {
$data['view_files'] .= "_jqm";
$template = 'public_jqm';
} else {
$template = 'public_boostrap';
}
$token = $this->uri->segment(3);
if($token!='') {
$session_id = $this->_check_and_get_session_id($token);
} else {
$session_id = $this->session->session_id;
}
$this->load->module('site_security');
$shopper_id = $this->site_security->_get_user_id();
if(!is_numeric($shopper_id)) {
$shopper_id = 0;
}
$table = 'store_basket';
$data['query'] = $this->_fetch_cart_contents($session_id, $shopper_id, $table);
//count the items in basket or cart
$data['num_rows'] = $data['query']->num_rows();
$data['showing_statement'] = $this->_get_showing_statement($data['num_rows']);
$this->load->module('templates');
$this->templates->$template($data);
}
I'm trying to display one of these boxes : (Image here) for every product. But when I add another product in the database, it doesn't seem to add another on view for my products page. Here you see my database, but only one image on my products page. The page looks as same as the first image posted above. If anyone knows why my products aren't showing for each product, only the first one, then please let me know. I know my code is not secure, not neat. I will do that after I'm done getting this to work so don't judge me on that. Only the issue I asked. Thanks.
My PHP code is all in this one function which I call in my div containers :
function grabProducts($con) {
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="col-md-12" id="please_wait">
<div class="panel panel-warning">
<div class="panel-heading">
<h3 class="panel-title"><i>Loading, Please Wait...</i></h3>
</div>
<div class="panel-body">
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#please_wait').fadeOut(7000);
$('#content_purchase').hide(0).delay(5000).fadeIn("slow");
});
</script>
<?php
$users = $this->grabUserInfos($con);
foreach ($users as $user) {
$username = $user[1];
$email = $user[3];
}
$site_config = new site_config();
$member_config = new member_config();
$result = mysqli_query($con, "SELECT * FROM products");
$count = mysqli_num_rows($result);
$site_callback = $site_config->grabSiteSettings_manual($con, 'site_url').'/pizza/includes/checkout.php';
$site_return_success = $site_config->grabSiteSettings_manual($con, 'site_url').'/pizza/products.php?status=complete';
$site_return_canceled = $site_config->grabSiteSettings_manual($con, 'site_url').'/pizza/products.php?status=canceled';
// See if there are any products in the database
if ($count > 0) {
// While loop for each product element
while ($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$picture = $row['picture_location'];
$price = $row['price'];
$stock_monitering = $row['stock_monitering'];
//$stock = $row['stock'];
// Count the number links in each product
$product_count = mysqli_query($con, "SELECT COUNT(*) FROM ebook WHERE used_status = '0'");
$row_product_count = mysqli_fetch_row($product_count);
$count_product_stock = $row_product_count[0];
$stock = $count_product_stock;
$new_stock = $stock - 1;
$getValidatedCheck_ = mysqli_query($con, "SELECT txn_id, hasValidated, item_name, amount, currency, payment_date FROM payment_logs WHERE userId = '$username' ORDER BY id DESC LIMIT 1");
// Count the number of payment_logs that correspond to the logged in user
$payment_log_count = mysqli_query($con, "SELECT COUNT(*) FROM payment_logs WHERE userId = '$username'");
$row = mysqli_fetch_row($payment_log_count);
$count_payment_logs = $row[0];
$now = strtotime("-10 minutes");
// If there are no transactions for that user show the products like normal
if($count_payment_logs <= 0) {
// If there is not enough stock, show out of stock
if($stock <= 0) {
$display = "out_of_stock";
} else if($stock > 0) {
$display = "show_products";
}
} else if($count_payment_logs >= 1) {
// While loop for our successful payment_logs for each user
while ($row = mysqli_fetch_array($getValidatedCheck_)) {
$txn_id = $row['txn_id'];
$validated_check = $row['hasValidated'];
$item_name = $row['item_name'];
$item_price = $row['amount'];
$item_currency = $row['currency'];
$payment_date = $row['payment_date'];
// If they've not already seen the success message, show them it now and update their hasValidated from 0 to 1 so they don't see it again
if ($validated_check == '0') {
// If stock monitering is on, update our stock to 1 less than we had before the purchase
if($stock_monitering == '1') {
mysqli_query($con, "UPDATE products SET stock = '$new_stock' WHERE name = '$name'");
}
$product_count = mysqli_query($con, "UPDATE ebook SET used_status = '1', assigned_to = '$username', transaction_id = '$txn_id' WHERE used_status = '0'");
$display = "show_success";
} else {
if($stock <= 0) {
$display = "out_of_stock";
} else if($stock > 0) {
$display = "show_products";
}
}
}
}
switch($display) {
case "show_products":
?>
<div class="col-md-3" id="content_purchase" style="display: none;">
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Price: <i>$<?php echo $price; ?></i>
<div class="fRight" style="float: right;"><i><?php echo $name; ?></i> Stock
(<?php echo $stock; ?>)
</div>
</h3>
</div>
<center>
<div class="panel-body">
<img src="<?php echo $picture; ?>"
style="width: 85%; height: 100px; margin: 15px 0px 15px 0px; border-radius: 5px; border: 2px solid #ED4949;">
<form name="paypal_form" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="POST">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="<?php echo $site_config->grabSiteSettings_manual($con, 'paypal_address'); ?>">
<input type="hidden" name="item_name" value="<?php echo $name; ?>">
<input type="hidden" name="item_number" value="<?php echo $id; ?>">
<input type="hidden" name="amount" value="<?php echo $price; ?>">
<input type="hidden" name="quantity" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="custom" value="username=<?php echo $username; ?>&product= <?php echo $name; ?>">
<input type="hidden" name="notify_url" value="<?php echo $site_callback; ?>">
<input type="hidden" name="return" value="<?php echo $site_return_success; ?>">
<input type="hidden" name="cancel_return" value="<?php echo $site_return_canceled; ?>">
<button type="submit" class="btn btn-danger"
style="vertical-align : bottom; margin-bottom: 15px; display: block; width: 85%;">
<i class="fa fa-paypal"></i>aypal
</button>
<form>
</div>
</center>
</div>
</div>
';
break;
case "show_success":
?>
<div class="col-md-12" id="content_purchase" style="display: none;">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title"><i>PAYMENT SUCCESS!</i></h3>
</div>
<div class="panel-body">
<p>You've successfully purchased <i><?php echo $item_name; ?></i> for <i><?php echo $item_price; ?> <i><?php echo $item_currency; ?></i>. We have emailed you your receipt to <?php echo $email; ?>. You can click here to download your purchased files.<br>Click here to purchase again.</p>
</div>
</div>
</div>
<?php
mysqli_query($con, "UPDATE payment_logs SET hasValidated = '1' WHERE userId = '$username' ORDER BY id DESC LIMIT 1");
break;
case "no_products":
?>
<div class="col-md-12" id="content_purchase" style="display: none;">
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title"><i>Currently No Products For Sale</i></h3>
</div>
<div class="panel-body">
<p>There are currently no products up for sale.</p>
</div>
</div>
</div>
<?php
break;
case "out_of_stock":
?>
<div class="col-md-3" id="content_purchase" style="display: none;">
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Price: <i>$<?php echo $price; ?></i>
<div class="fRight" style="float: right;"><i><?php echo $name; ?></i> Stock
(<?php echo $stock; ?>)
</div>
</h3>
</div>
<center>
<div class="panel-body">
<img src="<?php echo $picture; ?>"
style="width: 85%; height: 100px; margin: 15px 0px 15px 0px; border-radius: 5px; border: 2px solid #ED4949;">
<p style="margin: 0px 15px 0px 15px;"><i><?php echo $name; ?></i> is currently out of stock. Please come back later and try again.</p>
</div>
</center>
</div>
</div>
<?php
break;
}
}
} else {
$display = 'no_products';
}
}
You should also loop your UI box so that you can have the same number of the product in the database and the box printed.
$sql = "Select * from product";
foreach('fetch all product from DB'){
?>
<div class="col-md-3" id="content_purchase" style="display: none;">
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Price: <i>$<?php echo $price; ?></i>
<div class="fRight" style="float: right;"><i><?php echo $name; ?></i> Stock
(<?php echo $stock; ?>)
</div>
</h3>
</div>
<center>
<div class="panel-body">
<img src="<?php echo $picture; ?>"
style="width: 85%; height: 100px; margin: 15px 0px; border-radius: 5px; border: 2px solid #ED4949;">
<form name="paypal_form" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="POST">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="<?php echo $site_config->grabSiteSettings_manual($con, 'paypal_address'); ?>">
<input type="hidden" name="item_name" value="<?php echo $name; ?>">
<input type="hidden" name="item_number" value="<?php echo $id; ?>">
<input type="hidden" name="amount" value="<?php echo $price; ?>">
<input type="hidden" name="quantity" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="custom" value="username=<?php echo $username; ?>&product= <?php echo $name; ?>">
<input type="hidden" name="notify_url" value="<?php echo $site_callback; ?>">
<input type="hidden" name="return" value="<?php echo $site_return_success; ?>">
<input type="hidden" name="cancel_return" value="<?php echo $site_return_canceled; ?>">
<button type="submit" class="btn btn-danger"
style="vertical-align : bottom; margin-bottom: 15px; display: block; width: 85%;">
<i class="fa fa-paypal"></i>aypal
</button>
<form>
</div>
</center>
</div>
</div>
<?php
} //end loop
sorry I forgot the syntax. :D but that's the logic.
I created a website selling components. Each component has 9 products. How can I add a dropdown button which can arrange the product showing by its Price or Name?
<?php
$query = "SELECT * FROM products ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id=<?php echo $row["id"]; ?>">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<h5 class="text-info"><?php echo $row["p_name"]; ?></h5>
<img src="<?php echo $row["image"]; ?>" class="img-responsive">
<h5 class="text-danger">$ <?php echo $row["price"]; ?></h5>
<div class="col-xs-8">
<input type="text" name="quantity" class="form-control" value="1">
</div>
<input type="hidden" name="hidden_name" value="<?php echo $row["p_name"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>">
<input type="submit" name="add" class="btn btn-primary" value="Add to Cart" align="right">
</div>
</form>
</div>
<?php
}
}
?>
<?php
}
?>
</div>
</div>
Perhaps you could use Javascript as well and add a few select boxes to give Users the chance to choose the Attribute they want to sort by and also the Direction of the Sorting as in ASC or DESC. The Code Snippet below might shed some light:
<?php
$query = "SELECT * FROM products ORDER BY id ASC";
$result = mysqli_query($connect, $query);
// CREATE VARIABLES TO HOLD THE SELECT OPTIONS VALUES FOR THE SORTING...
$sortParam1 = 'price';
$sortParam2 = 'name';
$sortDir1 = 'ASC';
$sortDir2 = 'DESC';
// START BUILDING THE OUTPUT...
$output = "<div class='col-md-12'>"; //<== WRAPPER FOR SORING & DIRECTION BOXES
$output .= "<form method='post' action='' id='sorting_form'>"; //<== FORM FOR THE SORTING: SUBMITS TO SAME SCRIPT
// SORTING
$output .= "<div class='col-md-6'>";
$output .= "<select name='sorting' id='sorting'class='form-control'>";
$output .= "<option value='id'>Sorting</option>";
$output .= "<option value='{$sortParam1}'>{$sortParam1}</option>";
$output .= "<option value='{$sortParam2}'>{$sortParam2}</option>";
$output .= "</select>";
$output .= "</div>";
// DIRECTION
$output .= "<div class='col-md-6'>";
$output .= "<select name='direction' id='direction'class='form-control'>";
$output .= "<option value='ASC'>Sort Direction</option>";
$output .= "<option value='{$sortDir1}'>{$sortDir1}</option>";
$output .= "<option value='{$sortDir2}'>{$sortDir2}</option>";
$output .= "</select>";
$output .= "</div>";
$output .= "</form>"; //<== CLOSE SORTING FORM...
$output .= "</div>"; //<== CLOSE WRAPPER...
$rowData = "";
// WE USE JQUERY BELOW TO SUBMIT THE SORTING FORM ONCE USER
// SELECTS ANY OPTION FROM.... SO WE NOW HANDLE THAT SCENARIO HERE USING PHP
if(isset($_POST['sorting']) || isset($_POST['direction']) ){
$sortDirection = isset($_POST['direction']) ? $_POST['direction'] : $sortDir1; // DEFAULTS TO ASC
$sortField = isset($_POST['sorting']) ? $_POST['sorting'] : 'id'; // DEFAULTS TO id
$query = "SELECT * FROM products ORDER BY {$sortField} {$sortDirection}";
$result = mysqli_query($connect, $query);
}
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)) {
// USE HEREDOC TO CAPTURE THE DATA WITHIN THE LOOP...
$rowData .=<<<R_DATA
<div class="col-md-4">
<form method="post" action="shop.php?action=add&id={$row["id"]}">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<h5 class="text-info">{$row["p_name"]}</h5>
<img src="{$row["image"]}" class="img-responsive">
<h5 class="text-danger">\$ {$row["price"]}</h5>
<div class="col-xs-8">
<input type="text" name="quantity" class="form-control" value="1">
</div>
<input type="hidden" name="hidden_name" value="{$row["p_name"]}">
<input type="hidden" name="hidden_price" value={$row["price"]}">
<input type="submit" name="add" class="btn btn-primary" value="Add to Cart" align="right">
</div>
</form>
</div>
R_DATA;
} // CLOSE WHILE LOOP
} // CLOSE IF CONDITIONAL LOGIC
// ADD THE DATA GATHERED FROM WHILE LOOP ($rowData) TO THE OUTPUT: $output
$output .= $rowData;
$output .= "</div>\n</div>"; // THESE APPEAR IN YOUR CODE BUT SEEM IRRELEVANT HERE...
// DISPLAY THE OUTPUT
echo $output;
?>
<!-- ENTER JAVASCRIPT: JQUERY -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(e){
var sortForm = $("#sorting_form");
var sortBox = $("#sorting");
var directionBox = $("#direction");
var bothBoxes = sortBox.add(directionBox);
// IF EITHER OF THE SORTING OR DIRECTION IS CHANGED
// JUST SUBMIT THE FORM
bothBoxes.on("change", function(evt){
sortForm.submit();
});
});
})(jQuery);
</script>
I have run program in simpal query it is work.
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['search']))
{
$category = $_POST['category_id'];
$country = $_POST['country_id'];
$sql = "SELECT DISTINCT p.name,p.product_id,pr.image
FROM oc_product_description p, oc_product_filter pf ,oc_product_to_category ptc, oc_product pr
WHERE p.product_id=pf.product_id AND p.product_id=ptc.product_id AND p.product_id=pr.product_id
AND ptc.category_id=$category AND pf.filter_id=$country";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "</br>name: " . $row["name"];
$abc = $row["product_id"];
//echo "</br>id: " . $row["image"];
//echo "</br>id: " . $row["description"];
?>
<div>
<div class="row" style="border: 1px solid;height: 210px;padding: 10px 10px;">
<div class="product-block item-full" itemtype="http://schema.org/Product" itemscope="">
<div class="block-img" style="width: 13%;float: left;margin-right: 10px;" >
<?php
$temp = $row["name"];
$str = explode(" ",$temp);
$pname = implode("",$str);
?>
<div class="image" >
<a class="img" itemprop="url" title="<?php echo $row['name']; ?>" href="http://hrmssystem.com/<?php echo $pname; ?>">
<img class="img-responsive" itemprop="image" src="image/<?php echo $row['image']; ?>" title="<?php echo $row['name']; ?>" alt="<?php echo $row['name']; ?>" />
</a>
</div>
</div>
<div class="product-meta" style="height: 30%;width: 85%;float: left;">
<div style="height: 100%; width: 100%; ">
<h3 class="name" itemprop="name">
<a href="http://hrmssystem.com/<?php echo $pname; ?>">
<?php echo $row['name'];
?>
</a>
</h3>
<?php
$sql2 = "SELECT description from oc_product_description where product_id = $abc ";
$res = $conn->query($sql2);
if ($res->num_rows > 0) {
// output data of each row
while($col = $res->fetch_assoc()) {
//echo $col["description"];
if( isset($col['description']) ){
$des = utf8_substr( strip_tags($col['description']),0,220);
?>
<p style="display: block;" class="description" itemprop="description"><?php echo $des; ?>...</p>
<?php }
} } ?>
<div class="cart" style="float: right;margin-top: -30px;">
<a style="color: #3498DB;" class="btn btn-default" href="http://www.hrmssystem.com/Get-Quote">Get Quote</a><?php //echo $button_cart; ?>
</br>
<a style="color: #3498DB;" class="btn btn-default" href="http://www.hrmssystem.com/Request-demo">Request Demo</a><?php //echo $button_cart; ?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}
} else {
echo "0 results";
}
}
$conn->close();
?>
Above Code is running. But I have select only category than no result. But I have Select category and country than i have find result of search.
<?php
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['search']))
{
$category = $_POST['category_id'];
$country = $_POST['country_id'];
$sql = "SELECT DISTINCT p.name,p.product_id,pr.image, pf.filter_id
FROM oc_product_description p, oc_product_filter pf ,oc_product_to_category ptc, oc_product pr ";
//$val = array();
if(isset($category) && !empty($category)){
$sql .= ' WHERE p.product_id=pf.product_id AND p.product_id=ptc.product_id AND p.product_id=pr.product_id AND ptc.category_id=$category ';
}else(isset($country) && !empty($country)){
$sql .= ' WHERE p.product_id=pf.product_id AND p.product_id=ptc.product_id AND p.product_id=pr.product_id AND pf.filter_id=$country';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "</br>name: " . $row["name"];
$abc = $row["product_id"];
//echo "</br>id: " . $row["image"];
//echo "</br>id: " . $row["description"];
?>
<div>
<div class="row" style="border: 1px solid;height: 210px;padding: 10px 10px;">
<div class="product-block item-full" itemtype="http://schema.org/Product" itemscope="">
<div class="block-img" style="width: 13%;float: left;margin-right: 10px;" >
<?php
$temp = $row["name"];
$str = explode(" ",$temp);
$pname = implode("",$str);
?>
<div class="image" >
<a class="img" itemprop="url" title="<?php echo $row['name']; ?>" href="http://hrmssystem.com/<?php echo $pname; ?>">
<img class="img-responsive" itemprop="image" src="image/<?php echo $row['image']; ?>" title="<?php echo $row['name']; ?>" alt="<?php echo $row['name']; ?>" />
</a>
</div>
</div>
<div class="product-meta" style="height: 30%;width: 85%;float: left;">
<div style="height: 100%; width: 100%; ">
<h3 class="name" itemprop="name">
<a href="http://hrmssystem.com/<?php echo $pname; ?>">
<?php echo $row['name'];
?>
</a>
</h3>
<?php
$sql2 = "SELECT DISTINCT description from oc_product_description where product_id = $abc ";
$res = $conn->query($sql2);
if ($res->num_rows > 0) {
// output data of each row
while($col = $res->fetch_assoc()) {
//echo $col["description"];
if( isset($col['description']) ){
$content = substr(strip_tags(htmlspecialchars_decode($col['description'])),0,220) . "...";
?>
<p style="display: block;width: 87%;" class="description" itemprop="description"><?php echo $content; ?></p>
<?php }
} } ?>
<div class="cart" style="float: right;margin-top: -90px;">
<a style="color: #3498DB;" class="btn btn-default" href="http://www.hrmssystem.com/Get-Quote">Get Quote</a><?php //echo $button_cart; ?>
</br>
<a style="color: #3498DB;" class="btn btn-default" href="http://www.hrmssystem.com/Request-demo">Request Demo</a><?php //echo $button_cart; ?>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}
} else {
echo "No Result Found";
}
}
$conn->close();
?>
Try this:
$string = "";
if(isset($category) && !empty($category))
{
$string .= ' AND ptc.category_id=$category ';
}
if(isset($country) && !empty($country))
{
$string .= ' AND pf.filter_id=$country ';
}
$sql = "SELECT DISTINCT p.name,p.product_id,pr.image, pf.filter_id
FROM oc_product_description p, oc_product_filter pf ,oc_product_to_category ptc, oc_product pr
WHERE p.product_id=pf.product_id AND p.product_id=ptc.product_id AND p.product_id=pr.product_id
$string
";
Please remove if - else condition and use only if condition and use variable to store the condition.
In this code I tried to filter some data records from the database using CategoryId but it returns all the category Id's. In my database Category Id's are INT field.
If I echo $data['Category']; then it shows all the categoryId's But after the variable comparison it not work.
I mean if($cat == 1) is Not working(It's not filter/Show data)
//Some coding here
<section id="section-1">
<div class="vs-content">
<div class="widgets-container">
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$sql = "SELECT Id,Title,description,Image,Category from News ";
$query = mysql_query($sql);
?>
<div class="blocks">
<?php while($data = mysql_fetch_array($query)){
$cat = $data['Category'];
if($cat == 1){
?>
<h3 style="margin-left: 10px;"><?php echo $data['Title'] ?></h3>
<div style="width: 50%; margin-right: auto; margin-left: auto;">
<img src="images/drink2.jpg" /></div>
<img src="data:image/jpeg;base64,<?php base64_encode( $data['Image'] )?>"/>
<p style="color: white; font-size: 0.6em;"><?php echo $data['Description'] ?></p>
<?php
}
}
?>
</div>
<div class="blocks">
<?php while($data = mysql_fetch_array($query)){
$cat = $data['Category'];
if($cat == 2){
?>
<h3 style="margin-left: 10px;"><?php echo $data['Title'] ?></h3>
<div style="width: 50%; margin-right: auto; margin-left: auto;">
<img src="images/drink2.jpg" /></div>
<img src="data:image/jpeg;base64,<?php base64_encode( $data['Image'] )?>"/>
<p style="color: white; font-size: 0.6em;"><?php echo $data['Description'] ?></p>
<?php
}
}
?>
</div>
<div class="blocks">
<?php while($data = mysql_fetch_array($query)){
$cat = $data['Category'];
if($cat == 3){
?>
<h3 style="margin-left: 10px;"><?php echo $data['Title'] ?></h3>
<div style="width: 50%; margin-right: auto; margin-left: auto;">
<img src="images/drink2.jpg" /></div>
<img src="data:image/jpeg;base64,<?php base64_encode( $data['Image'] )?>"/> -->
<p style="color: white; font-size: 0.6em;"><?php echo $data['Description'] ?></p>
<?php
}
}
?>
</div>
</div>
</div>
// Some coding here
Why not filter the records in your database query? This would mean changing your database query as follows:
$sql = "SELECT Id,Title,description,Image,Category from News WHERE Category = 1";
By taking this approach less data will be returned to PHP and the database call will execute a little faster :)
Update: You only really need the three different <div class="blocks"> sections if the contents within them is going to be different. Otherwise you could simply use a single while loop and output the content for all categories in sequence using the data as ordered by the SQL statement.
//Some coding here
<section id="section-1">
<div class="vs-content">
<div class="widgets-container">
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("mydb") or die(mysql_error());
$sql = "SELECT Id,Title,description,Image,Category from News ORDER BY Category";
$query = mysql_query($sql);
?>
<div class="blocks">
<?php while($data = mysql_fetch_array($query)){
?>
<h3 style="margin-left: 10px;"><?php echo $data['Title'] ?></h3>
<div style="width: 50%; margin-right: auto; margin-left: auto;">
<img src="images/drink2.jpg" /></div>
<img src="data:image/jpeg;base64,<?php base64_encode( $data['Image'] )?>"/>
<p style="color: white; font-size: 0.6em;"><?php echo $data['Description'] ?></p>
<?php
}
?>
</div>
</div>
</div>
</section>
// Some coding here
If you only need data rendered for a single category then use the WHERE clause in SQL (See first example) to filter the data you require to reduce the SQL call and improve performance.
Why cant you check the condition in select query, Try this,
$sql = "SELECT Id,Title,description,Image,Category from News where Category='1'";
Update:
<div class="blocks">
<?php
while($data = mysql_fetch_array($query)){
$cat = $data['Category'];
if($cat == 1){ ?>
//Your code
<?php }else if($cat == 2){ ?>
// Your code
<?php }else{ ?>
<?php }?>
<?php }?>
</div>