automatically populate text box based on select entry - javascript

Is there a way within php to get a value picked up from database automatically?
Basically, If I have a select box & I select option "Laptop-01" , is there a way within PHP to check the database for that row and then automatically pick up the serial number of Laptop-01 and populate it within the text box for the devices serial number.
At the moment I've just got two text boxes and user would need to manually enter both the product number (Laptop-01) & then the serial number.
I've currently got the following code;
PHP
<?php
$selectquery = "SELECT * FROM `loanproducts`";
$selectresult = mysqli_query($connection, $selectquery);
$selectusersquery = "SELECT * FROM `loanusers`";
$selectusersresult = mysqli_query($connection, $selectusersquery);
if (isset($_POST['editloan'])):
$loanid = $_POST["loanid"];
$username = $_POST["username"];
$product=$_POST["product"];
$product_desc=$_POST["product_desc"];
$serial=$_POST["serial"];
$date_collected=$_POST["date_collected"];
$date_return = $_POST["date_return"];
$returned = $_POST["returned"];
$edit_query="UPDATE loans SET
username = '$username',
product = '$product',
product_desc = '$product_desc',
serial = '$serial',
date_collected ='$date_collected',
date_return = '$date_return',
returned = '$returned'
WHERE loanid ='$loanid'";
$edit_result= mysqli_query($connection, $edit_query);
if ($edit_result) :
header ('location: editloan.php?confirm=Loan successfully updated');
else :
echo "<b>This didn`t work, error: </b>";
echo mysqli_error($connection);
endif;
endif;
$loanid=$_GET['loanid'];
$my_query="select * from loans where loanid=$loanid";
$result= mysqli_query($connection, $my_query);
while ($myrow = mysqli_fetch_array($result)):
$username = $myrow["username"];
$product = $myrow["product"];
$product_desc = $myrow["product_desc"];
$serial = $myrow["serial"];
$date_collected=$myrow["date_collected"];
$date_return=$myrow["date_return"];
$returned=$myrow["returned"];
endwhile;
?>
HTML
<html>
<h2 align="center">Edit Product Form</h2>
<body>
<div id="loginp"<p align="center">Edit this loan for the Coleg Sir Gar Loan System</p></div>
<form method="POST" action="editloaninfo.php">
<div id="editp"><p align="center">
<label class="labelform">Username:</label><select name="username" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectusersresult))
{ if ( $row1[1] == $username )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product:</label><select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
{ if ( $row1[1] == $product )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product Description:</label><input class="inputform" type="text" name="product_desc" placeholder="Product Description..." autocomplete="off" required size="18" value="<?php echo $product_desc; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Serial Number:</label><input class="inputform" type="text" name="serial" placeholder="Serial Number..." autocomplete="off" required size="18" value="<?php echo $serial; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Collected:</label><input class="inputform" type="date" name="date_collected" autocomplete="off" size="30" value="<?php echo $date_collected; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Returned:</label><input class="inputform" type="date" name="date_return" autocomplete="off" size="30" value="<?php echo $date_return; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Returned:</label><select name="returned" style="width: 150px">
<option value="Yes" <?php echo $returned === 'Yes' ? 'selected="selected"' : '' ?>>Yes</option>
<option value="No" <?php echo $returned === 'No' ? 'selected="selected"' : '' ?>>No</option>
</select></p></div>
<br>
<input type="hidden" name=loanid value= "<?php echo $loanid; ?>" >
<div id="editp"><input class="inputform" type="submit" name="editloan" value="Save Changes">
<input class="inputform" type="button" name="Cancel" value="Cancel" onClick="window.location.href='editloan.php'"></div>
</form>
</body>
</html>
</div>

Basically you want to do is :
When User select 'Laptop-01' you page must update all INPUTS with information related to user's laptop (like Serial number).This can be done by adding AJAX
Please note : This answer will give you idea about how to Populate data from data base then you can do this for any information you needed.
<form>
<select id='product_name' onchange="get_data()">
<option value='Laptop-01'>Laptop-01</option>
</select>
<input name='serial_no' id='serial_no'>
<input name='product_no' id='product_no'>
</form>
<script src="js/ajax.js"></script>
<script>
function get_data(){
//In very short what this do is :
//get values
var serial_no = document.getElementById('product_name').value;
//create an Object
var ajax = ajaxObj("POST", "yourpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//ajax.responsetex is things you echo from script next to it
var index1 = ajax.responseText.split(",");
//index1 is array holding values
//index1[0]=$serial_no
//index1[1]=$product_no
//Now set value of your serian_no INPUT to $serial_no = index1[0];
document.getElementById('serial_no').value = index1[0];
document.getElementById('product_no').value = index1[1]
}
}
//ajax.send = POST/GET method
ajax.send("product_name="+product_name);
}
</script>
<?php
if(isset($_POST['product_name'])){
$sql = "SELECT serial_no,product_no FROM loanuser WHERE username='$username'";
$query = ($connection , $query);
while ($myrow = mysqli_fetch_array($query)){
$serial_no = $myrow["serial_no"];
$product_no = $myrow["product_no"];
}
//form a (,) separated list and echo it.
echo $serial_no.",".$product_no;
exit();
}
?>
Ajax.js
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
If you want me to add more explanation on AJAX used in this page , please add request in comment section i will edit it to more better answer

Related

How to calculate amount by javascript?

As u can see i have this form that calculate number of employees multiply by test that will be select by user. number of employees will be input by user and test are coming from database. each test have their individual price set in database. I used script for dropdown list.
If user put any value in no.of employees and check on anytest then in total amount sum should be calculate onclick buytest?
<form action="add_corporate_test.php" method="POST">
<script type="text/javascript">
$(document).ready(function () {
$('#example-onDeselectAll').multiselect({
includeSelectAllOption: true,
onDeselectAll: function () {
alert('please select any test!');
}
});
});
</script>
<div class="row">
<h5 class="cor_label">No. of Emp/Students:</h5>
<input
type="text" id="no_emp"
placeholder="No. of Employees/Students"
class="normal" required
>
<h5 class="cor_label">Email Address:</h5>
<input
type="text"
id="no_emp2"
placeholder="Email Address"
class="normal" value="<?php echo $_SESSION[email]; ?>"
required
disabled
>
<h5 class="cor_label">Select Test:</h5>
<select id="example-onDeselectAll" multiple="multiple">
<?php
$sql = mysql_query("select * from `test` ");
while ($data = mysql_fetch_assoc($sql)) {
$sum = 0;
?>
<option value="<?php echo $data['test_name']; ?>">
<?php echo $data['test_name']; ?>
</option>
<?php } ?>
</select>
<h5 class="cor_label">Total Amount:</h5>
<input
type="text"
id="no_emp3"
class="normal"
name="total_amount"
placeholder="total amount"
value="<?php echo $sum; ?>"
disabled
>
<button class="btn btn-primary" type="submit" name="corporate_buy">
Buy Test
</button>
</div>
</form>
Hi bro, use for loop for script b'coz u have multiple select option
`
<script>
$('#example-onDeselectAll').change(function() {
var value = $(this).val();
var i=0;
var len = value.length;
var no_emp = $("#no_emp").val();
for(i; i < len; i++){
var res = value[i] .split("_");
var tot_amount += res[1]*no_emp;
}
$("#no_emp3").val(tot_amount);
});
</scrit>
`
get the test and value on select option. on select split the value using javascript. and then sum the amount and no.of.employee
`
<select id="example-onDeselectAll" multiple="multiple" >
<?php
$sql=mysql_query("select * from `test` ");
while($data=mysql_fetch_assoc($sql))
{
$sum=0;
?>
<option value="<?php echo $data['test_name'];?>_<?php echo $data['price'];?>"><?php echo $data['test_name'];?></option>
<?php }?>
</select>
<script>
$('#example-onDeselectAll').change(function() {
var value = $(this).val();
var no_emp = $("#no_emp").val();
var res = value .split("_");
var tot_amount = res[1]*no_emp;
$("#no_emp3").val(tot_amount);
});
</scrit>
`

making multiple choice with data from database

I want to make a multiple choice and the question is coming from database. I am sure that my database name is correct, but when i click next, the question is not changing, it is directly going to the end/result of question and the question is not random too. The last question that I inserted into the database is displayed in webpage. Please help
this is my code:
<?php
require_once('includes/db_conn.php');
$query = "select * from question";
$query_result = $dbc->query($query);
$num_questions_returned = $query_result->num_rows;
if ($num_questions_returned < 1){
echo "There is no question in the database";
exit();}
$questionsArray = array();
while ($row = $query_result->fetch_assoc()){
$questionsArray[] = $row;
}
$correctAnswerArray = array();
foreach($questionsArray as $question){
$correctAnswerArray[$question['question']] = $question['correct_answer'];
}
$questions = array();
foreach($questionsArray as $question) {
$questions[$question['question']] = $question['question'];
}
$choices = array();
foreach ($questionsArray as $row) {
$choices[$row['question']] = array($row['wrong_answer1'], $row['wrong_answer2'], $row['wrong_answer3'], $row['correct_answer']);
}
error_reporting(0);
$address = "";
$randomizequestions ="yes";
$a = array(
1 => array(
0 => $question['question'],
1 => $row['wrong_answer1'],
2 => $row['wrong_answer2'],
3 => $row['wrong_answer3'],
4 => $row['correct_answer'],
6 => 4
),
);
$max=1;
$question=$_POST["question"] ;
if ($_POST["Randon"]==0){
if($randomizequestions =="yes"){$randval = mt_rand(1,$max);}else{$randval=1;}
$randval2 = $randval;
}else{
$randval=$_POST["Randon"];
$randval2=$_POST["Randon"] + $question;
if ($randval2>$max){
$randval2=$randval2-$max;
}
}
$ok=$_POST["ok"] ;
if ($question==0){
$question=0;
$ok=0;
$percentage=0;
}else{
$percentage= Round(100*$ok / $question);
}
?>
<HTML><HEAD>
<SCRIPT LANGUAGE='JavaScript'>
<!--
function Goahead (number){
if (document.percentaje.response.value==0){
if (number==<?php print $a[$randval2][6] ; ?>){
document.percentaje.response.value=1
document.percentaje.question.value++
document.percentaje.ok.value++
}else{
document.percentaje.response.value=1
document.percentaje.question.value++
}
}
if (number==<?php print $a[$randval2][6] ; ?>){
document.question.response.value="Correct"
}else{
document.question.response.value="Incorrect"
}
}
// -->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=FFFFFF>
<CENTER>
<H1><?php print "$title"; ?></H1>
<TABLE BORDER=0 CELLSPACING=5 WIDTH=500>
<?php if ($question<$max){ ?>
<TR><TD ALIGN=RIGHT>
<FORM METHOD=POST NAME="percentaje" ACTION="<?php print $URL; ?>">
<BR>Percentaje of correct responses: <?php print $percentage; ?> %
<BR><input type=submit value="Next >>">
<input type=hidden name=response value=0>
<input type=hidden name=question value=<?php print $question; ?>>
<input type=hidden name=ok value=<?php print $ok; ?>>
<input type=hidden name=Randon value=<?php print $randval; ?>>
<br><?php print $question+1; ?> / <?php print $max; ?>
</FORM>
<HR>
</TD></TR>
<TR><TD>
<FORM METHOD=POST NAME="question" ACTION="">
<?php print "<b>".$a[$randval2][0]."</b>"; ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="1" onClick=" Goahead (1);"><?php print $a[$randval2][1] ; ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="2" onClick=" Goahead (2);"><?php print $a[$randval2][2] ; ?>
<?php if ($a[$randval2][3]!=""){ ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="3" onClick=" Goahead (3);"><?php print $a[$randval2][3] ; } ?>
<?php if ($a[$randval2][4]!=""){ ?>
<BR> <INPUT TYPE=radio NAME="option" VALUE="4" onClick=" Goahead (4);"><?php print $a[$randval2][4] ; } ?>
<BR> <input type=text name=response size=8>
</FORM>
<?php
}else{
?>
<TR><TD ALIGN=Center>
The Quiz has finished
<BR>Percentage of correct responses: <?php print $percentage ; ?> %
<p>Home Page
<?php } ?>
</TD></TR>
</TABLE>
</CENTER>
</BODY>
</HTML>
this is my process add data to database:
<?php
include('includes/header.html');
error_reporting(-1);
ini_set('display_errors', 'On');
//Check for empty fields
if(empty($_POST['question'])||
empty($_POST['correct_answer']) ||
empty($_POST['wrong_answer1']) ||
empty($_POST['wrong_answer2']) ||
empty($_POST['wrong_answer3']))
{
echo "Please complete all fields";
exit();
}
//Create short variables
$question = $_POST['question'];
$correct_answer = ($_POST['correct_answer']);
$wrong_answer1 = ($_POST['wrong_answer1']);
$wrong_answer2 = ($_POST['wrong_answer2']);
$wrong_answer3 = ($_POST['wrong_answer3']);
//connect to the database
require_once('includes/db_conn.php');
//Create the insert query
$query = "INSERT INTO question VALUES ('$question', '$correct_answer', '$wrong_answer1','$wrong_answer2','$wrong_answer3')";
$result = $dbc->query($query);
if($result){
echo "Your quiz has been saved";
} else {
echo '<h1>System Error</h1>';
}
$dbc->close();
?>
Your first mistake is making array of $a why are you not using $choices which you had made in last for loop and for random questions handle $choices array and your submit button of next is outside the form so you will not get form values on next button.take it inside the form tag.
Another thing is on radio button click don't write anything just write your function on submit click event and then handle the next question after saving the previous answer.
These are what my suggestions.. for more help put here your database back up and its connected files so that I can help you in coding.

add to cart div refresh through Ajax

I am trying to add items in my cart through Ajax call. I tried it doing simple just with php and it works fine. But now i am trying to convert my code for php+ajax. I have an index.php page in which i am dynamically changing my content. When i click on some nav list. It redirects me to page like this: index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1 where page is passed through $_GET command every time a new page is called. I have a cart button on index.php header section.I want to refresh the div whose id is named as "cart". I am failing to do this through AJAX.Here i am pasting my code. Any suggestions or help will be appreciated.
cart div
<div id="cart">
<li style="color: #515151">
<img id="cart_img" src="images/cart.png">
Cart <span class='badge' id='comparison-count'>
<?php
if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
}
else {
$cart_count=0;
echo $cart_count;
}
?>
</span>
</li>
</div>
item.php
<div>
<?php
$query=mysqli_query($con,"select * from products where cat_id='$cat_id' and s_cat_id='$s_cat_id' ORDER BY product_name ASC");
if(mysqli_num_rows($query)!=0){
while($row=mysqli_fetch_assoc($query)){
?>
<div>
<input type="hidden" id="pid" value="<?php echo $row['productid'] ?>">
<h4><?php echo $row['product_name']; ?></h4>
<h4>Price<?php echo "$" . $row['product_price']; ?> </h4>
<form method="post" action="">
<input type="hidden" id="page" name="page" value="items">
<input type="hidden" id="action" name="action" value="add">
<input type="hidden" id="id" name="id" value="<?php echo $row['productid']; ?>">
<input type="hidden" id="name" name="name" value="<?php echo $row['product_name']; ?>">
<input type="hidden" id="cat_id" name="cat_id" value="<?php echo $row['cat_id']; ?>">
<input type="hidden" id="s_cat_id" name="s_cat_id" value="<?php echo $row['s_cat_id']; ?>">
<input type="hidden" id="category" name="category" value="<?php echo $cat ?>">
<td>Colors:
<select name="color" id="color">
<option selected value="choose">choose</option>
<option value="blue" id="blue">Red</option>
<option value="blue" id="blue">Blue</option>
<option value="yellow" id="yellow">Yellow</option>
<option value="green" id="green">Green</option>
</select></td>
<td>Size : <select name="size" id="size"><option selected value="Choose size">Choose</option>
<option value="XL" id="XL">XL</option>
<option value="L" id="L">L</option></select>
</td>
</div>
<input type="submit" class="add-to-cart" id="addtocart" value="Add to Cart">
</form>
</div>
</div>
add_cart.php
<?php
include ("db/db.php");
session_start();
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(isset($_POST['Action']) && $_POST['Action']=="add" && isset($_POST['S_cat_id']) && isset($_POST['Cat_id']) ){
$id=intval($_POST['Id']);
$size = $_POST['Size'];
$color = $_POST['Color'];
$sql="SELECT * FROM products WHERE productid={$id}";
$data = mysqli_query($con,$sql);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$index = $id." ".$color. " ".$size;
if( isset($_SESSION['cart'][$index]) && isset($_SESSION['cart'][$index]['color']) && $_SESSION['cart'][$index]['color'] == $color && isset($_SESSION['cart'][$index]['size']) && $_SESSION['cart'][$index]['size'] == $size){
$_SESSION['cart'][$index]['quantity']++;
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}else{
$_SESSION['cart'][$index] = array('quantity' => 1,'id'=> $id, 'price' => $row['product_price'], 'size' => $size, 'color' => $color, 'name' => $row['product_name']);
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}
}
else{
$message="Product ID is invalid";
$output = json_encode(array('type'=>'error', 'text' => $message));
die($output);
}
}
}
?>
Ajax
<script>
$(document).ready(function() {
$('#addtocart').click(function(e){
e.preventDefault();
var page = $("#page").val(),
action = $("#action").val(),
name= $("#name").val(),
cat_id= $("#cat_id").val(),
s_cat_id = $("#s_cat_id").val(),
id=$("#id").val(),
color=$("#color").val(),
size=$("#size").val(),
category = $("#category").val();
var proceed = true;
if(proceed){
post_data= { 'Page': page, 'Action': action,'Name': name, 'Cat_id': cat_id,'S_cat_id':s_cat_id, 'Category': category,'Id':id,'Color':color,'Size':size};
$.post('add_cart.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
//output=$('.alert-error').html(response.text);
}else{
output= $("#cart").load();
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
So, I'm assuming that your PHP code works and that the data is sent properly. I'm also assuming that your $.ajax call works. If one of these isn't true let me know.
You should be able to simply use jQuery to update the data of the div.
$("some div").html = response.text;
Or if you want to process the data before hand.
$("some div").html = process(response.text);
I am also assuming both the php and ajax codes work well...
All you need do is store the current value state of the div by saying something like
div=document.getElementById('elem_id');
oldv = div.firstChild.nodeValue;
and then appending the new result as
newv = oldv + responseMessage;
and finally saying
div.innerHTML=newv;
I believe this should work perfectly for your refresh request situation. You could adopt and adapt this idea in various conditions.
Note: I am also assuming that both the old and new values are either text/HTML contents not requiring any mathematical calculations

How to get all the value of same class by jQuery, and insert into an array and loop count is not correct in jQuery?

This is my form
<?php
$sql15 = "select * from reviewed_title";
$query15 = sqlsrv_query( $link, $sql15);
$count = 1;
while( $row = sqlsrv_fetch_array( $query15, SQLSRV_FETCH_ASSOC) ) { ?>
<div class = "title_body">
<div class = "title_top">
<div class="form-group">
<h3><?php
$title_id = $row['id'];
echo $count .". ".$row['title'];
?>
</h3>
</div>
</div>
<?php
$sql16 = "select * from item_reviewed WHERE title_id = $title_id";
$count2=1;
$query16 = sqlsrv_query( $link, $sql16);
$query17 = sqlsrv_query($link, $sql16, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
$row_num = sqlsrv_num_rows($query17);
//$row_num = 5;
while( $row2 = sqlsrv_fetch_array( $query16, SQLSRV_FETCH_ASSOC) ) { ?>
<div class = "title_bottom"
<?php if($row_num != $count2){?> style="border-bottom: 1px solid #000000;" <?php }?> >
<div class="form-group">
<input type="hidden" name="item_reviewed_id" value="<?php echo $row2['id'];?>" class="item_reviewed_id">
<div class = "title_bottom_left">
<h6> <?php echo $count.".".$count2 .". ".$row2['items'];
?></h6>
</div>
<div class= "title_bottom_center">
<label class="col-sm-2 label2" for="email">Y,N,N/A:</label>
<!--<select name="action" class="select <select_<?php echo $row2['id'];?>" id="select_<?php echo $count."".$count2;?>">-->
<select name="action" class="select" >
<option value="">Select</option>
<option value="yes">Yes</option>
</select>
</div>
<div class ="title_bottom_right">
<label class="col-sm-2 label3" for="email">Comment:</label>
<!--<textarea name="comment" class="form-control comment commentttt comment_<?php echo $row2['id'];?>>" <id="comment_<?php echo $count."".$count2;?>" placeholder="Comment"></textarea>-->
<textarea name="comment" class="form-control comment commentttt" placeholder="Comment"></textarea>
</div>
</div>
</div>
<?php $count2++;}?>
</div>
<?php $count++; }?>
Here I get 33 input fields, 33 select fields and 33 hidden fields.From table item_reviewed here i get 33 row. My jQuery code is ..
var ittem_id = new Array();
var j = 1;
$(".item_reviewed_id" ).each(function( i ) {
ittem_id[j] = $(this).val();
j++;
});
alert(j);
Here I get 1552 values. How i can get 33 values in jQuery ?
if you ve 1552 item and that loop output only 33 rows you must ve some other elements with class .item_reviewed_id in your page.
Use 2 classes to be sure you re selecting the right elements. JQuery map could be a very easy way to map your elements values
<input type="hidden" name="item_reviewed_id" value="<?php echo $row2['id'];?>" class="item_reviewed_id thisclass">
var ittem_id = $('.item_reviewed_id.thisclass').map(function(){
return $(this).val();
});
console.log(ittem_id); //this will be an array with your values!

How do I filter for similar products using checkboxes with PHP, AJAX and JS?

Here is an image of what I'm trying to accomplish -
Example of my Database Table -
My goal is to get a similar product to the product that is currently displaying without refreshing the page. I am trying to find similar products is by using check boxes.
I first got the id using $_GET['id'] which should be equal to one of the values in my table.
I then used PDO Fetch to get the product name, brand, quanity and price of that particular id and store it as a string.
What I need help with is using JQuery/AJAX to get the checkboxes that are checked and then send the information to a PHP file that would check if filter results match with any data from the table.
How can I do this?
This is my product.php file
<?php
require ('includes/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form>
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
</body>
</html>
I managed to solve this out, glad I didn't give up.
My product.php File
<?php
require ('/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form method="post" action="">
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
<div class="filter_container">
<div style="clear:both;"></div>
</div>
<script type="text/javascript" src="/js/filter.js"></script>
<input name="prod_name" value="<?php echo $prod_name ?>" style="display:none;"/>
<!--Hidden product name-->
</body>
</html>
Here is my JS File
$(document).ready(function() {
function showValues() {
var brand;
var quantity;
var calories;
var price;
//Gets product name
var prod_name = $('input[name="prod_name"]').val();
//Gets brand
if($('input[name="brand"]').is(':checked'))
{brand = $('input[name="brand"]').val();} else {brand = ""}
//Gets quantity
if($('input[name="quantity"]').is(':checked'))
{quantity = $('input[name="quantity"]').val();} else {quantity = ""}
//Gets calories
if($('input[name="calories"]').is(':checked'))
{calories = $('input[name="calories"]').val();} else {calories = ""}
//Gets price
if($('input[name="price"]').is(':checked'))
{price = $('input[name="price"]').val();} else {price = ""}
$.ajax({
type: "POST",
url: "/query.php",
data: {'brand':brand, 'quantity':quantity, 'calories':calories, 'prod_name':prod_name},
cache: false,
success: function(data){
$('.filter_container').html(data)
}
});
}
//Call function when checkbox is clicked
$("input[type='checkbox']").on( "click", showValues );
//Remove checked when checkbox is checked
$(".checkboxes").click(function(){
$(this).removeAttr('checked');
showValues();
});
});
Here is my PHP File
<?php
include('/db.php');
$prod_name = $_POST['prod_name'];
$Cbrand = $_POST['brand'];
$Cquantity = $_POST['quantity'];
$Ccalories = $_POST['calories'];
$Cprice = $_POST['price'];
if(!empty($Cbrand))
{
$data1 = "brand = '$Cbrand' AND";
}else{
$data1 = "";
}
if(!empty($Cquantity))
{
$data2 = "quantity = '$Cquantity' AND";
}else{
$data2 = "";
}
if(!empty($Ccalories))
{
$data3 = "calories = '$Ccalories' AND";
}else{
$data3 = "";
}
if(!empty($Cprice))
{
$data4 = "price = '$Cprice'";
}else{
$data4 = "";
}
$main_string = "WHERE $data1 $data2 $data3 $data4"; //All details
$stringAnd = "AND"; //And
$main_string = trim($main_string); //Remove whitespaces from the beginning and end of the main string
$endAnd = substr($main_string, -3); //Gets the AND at the end
if($stringAnd == $endAnd)
{
$main_string = substr($main_string, 0, -3);
}else if($main_string == "WHERE"){
$main_string = "";
}
else{
$main_string = "WHERE $data1 $data2 $data3 $data4";
}
if($main_string == ""){ //Doesn't show all the products
}else{
$sql = "SELECT COUNT(*) FROM products $main_string";
if ($res = $handler->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
$sql = "SELECT * FROM products $main_string";
foreach ($handler->query($sql) as $pro) {
if(($pro['prod_name'] == $prod_name) && ($res->fetchColumn() < 2))
{
//The product currently being displayed is blank when using the filter
}
else{
?>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<div class="form-result">
<td><?=strtoupper($pro['brand']) + " " + strtoupper($pro['prod_name']); ?></td>
</div>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<?php
}
}
} /* No rows matched -- do something else */
else {
?>
<div align="center"><h2 style="font-family:'Arial Black', Gadget, sans-serif;font-size:30px;color:#0099FF;">No Results with this filter</h2></div>
<?php
}
}
}
$handler = null;
$res = null;
?>

Categories

Resources