How Do i use JQuery to update the data - php

Ok so i am having a problem with figuring this problem out. I have a dynamic page that has records pulled out of a mysql database. The php code works great. The code is below
$catagory = $_GET['type'];
$query = "SELECT p.name, p.price, pc.quantity, p.image, p.descr FROM products ... where category_name = $catagory ";
$result = mysql_query($query);
$related = array();
while($row_r = mysql_fetch_assoc($result)){
$related[] = $row_r;
}
later on down the page I loop through them
<div class="main-blue">
<div class="blue-items">
<?php foreach ($related as $row_r) { ?>
<span class="digit"><span class="digit-r"><?php print $row_r["quantity"] ?></span></span>
<h3><?php print $row_r['name'] ?></h3>
.....
The problem is I have a
<div class="dropdown">
<ul>
<li>Grocery</li>
<li>Pizza</li>
<li>Quick Service</li>
<li>Retail</li>
<li>Salon</li>
<li>Bar</li>
</ul>
I need to be able to select one of the dropdowns like for example Bar I need to regrab the record from mysql and make the page load with the records for Bar without refreshing .
like
$catagory = "Bar";
$query = "SELECT p.name, p.price, pc.quantity, p.image, p.descr FROM products ... where category_name = $catagory ";

You need to use some sort of AJAX implementation to get this to work.
It will allow Js to query your PHP script to get a table or new JSON data to repopulate the table.
It doesn't look like you have any jQuery at the moment, give it a go to start with!
This question is very similar

Related

Getting linked data from multiple tables into seperate bootstrap cards

I very recently (as in, this week) started learning PHP and am doing a practice task.
(Therefore, apologies in advance, if I sound like I don't know what I'm talking about, that is true)
Here is a crude schematic of my tables:
I have a main table products, and there are 3 planned product types (book, disc, furniture), and each type has a special attribute, with their own tables. (size for discs, weight for books etc.)
So far through testing, I've managed to query out the object from my products table each into their separate bootstrap card components. What I am trying to accomplish now is to add the special attributes to their respective object cards.
This is where i've reached a dead end. The idea I have is to first create a seperate array $printtocard, then call all the products table records by type, then run a foreach through all the found records, and then run a switch inside the foreach where i check the product types and run cases based on type, which create new objects based on the linked table data, and add each of them to the $printtocard array.
Afterwards the plan is to call the array in the code that later outputs the objects.
Here is my code so far:
Main php code
class products {
var $arrayy;
var $sql;
var $typepr;
protected function get_prod($conn1){
$printtocard = array();
$call_type = 'SELECT type FROM products ORDER BY id';
$type_res = mysqli_query($conn1, $call_type);
$type_arr = mysqli_fetch_all($type_res, MYSQLI_ASSOC);
$this->typepr = $type_arr;
return $this->typepr;
foreach($typepr as $xxx){
switch($xxx){
case "disc":
/* $disc_ */$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_size AS a ON p.id = a.product_id;';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
case "book":
/* $book_ */$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_weight AS a ON p.id = a.product_id;';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
case "furniture":
/* $furniture_ */$sql = 'SELECT p.sku, p.name, p.price, a.height, a.width, a.length, FROM products AS p INNER JOIN attr_dims AS a ON p.id = a.product_id';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
}
}
//$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_size AS a ON p.id = a.product_id;';
//$call2 = 'SELECT sku, name, price FROM products ORDER BY id';
//$val_res = mysqli_query($conn1, $sql);
//$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$this->arrayy = $printtocard;
return $this->arrayy;
}
public function get_prod2($conn1)
{
$this->get_prod($conn1);
}
}
$fff= new products;
$fff->get_prod2($conn);
$sss= $fff->arrayy;
Snippet of the webpage code where I autogenerate the cards:
<div class="container">
<div class="row">
<?php
foreach($sss as $value){ ?>
<div class="col s6 md2">
<div class="card cardstyle z-depth-0">
<div class="card-content center">
<?php echo htmlspecialchars($value['sku']); ?>
<div>
<?php echo htmlspecialchars($value['name']); ?>
</div>
<div>
<?php echo htmlspecialchars($value['price']); ?>
</div>
<div>
<?php echo htmlspecialchars($value['value']); ?>
</div>
</div>
<div class="card-action right-align">
<a class="brand-text" href="#"> more info </a>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
The error message I currently get:
Warning
: Invalid argument supplied for foreach() in
C:\xampp\htdocs\uzdevumi\scandi_uzdevumi_kristianskonters\productlist\productlist.php
on line
108
A number of pointers
1. Its better to define your variables at the top depending on your intentions later (protected, private or public)
protected $arrayy;
protected $sql;
protected $typepr;
The return just before your "foreach" loop renders your loop pointless because it stops your function there and returns what you have.
return $this->typepr;
In connection to my previous point, you seem to think that "return" does some concatenation for you as shown by each "case" you have in your switch. No it does not it exits your function back to the calling scope.
return $this->printtocard;
The warning you have at the end means what it says, you are providing the "foreach" loop with an invalid argument. In other words it does not exist, thankfully its php (dynamically typed). But the problem is its undefined (has not value). Maybe its a typo and you wanted to loop through the array variable you got from sql calls.
foreach($typepr as $xxx)
Cross check typos and I did not get to check your html.

Joining tables and subqueries in MySQL

I know this question has been asked 1000s of times before but please bear with me as I have a slightly different scenarion.
Basically I have 2 MYSQL tables that I join (one called category and the other is products) and I create categories and subcategories menu in my PHP page using the following code:
<?php
$subcategories="";
$sql3="SELECT products.di_cat, GROUP_CONCAT(products.di_name) as di_name
FROM products LEFT JOIN category ON products.di_cat=category.names
GROUP BY products.di_cat";
$query3 = mysqli_query($db_conx, $sql3);
$existCount3 = mysqli_num_rows($query3);
if ($existCount3!=0) {
while($row3 = mysqli_fetch_array($query3, MYSQLI_ASSOC)){
$make_names = $row3["di_cat"];
$make_model = $row3["di_name"];
$subcategories = explode(",",$make_model);
print '<div class="col-md-3">
<span class="mega-menu-sub-title">'.$make_names.'</span>
<ul class="sub-menu">
<li>
<ul class="sub-menu">';
foreach($subcategories as $sub){
print '<li>'.$sub.'</li>';
}
print '</ul></li></ul></div>';
}
}
?>
This works fine and as it should.
Now I have a column in my products table called url.
This column is for creating clean URLs and the content of is basically the products names without any spaces or special characters.
I would like to use this in my code above but I don't understand why every time I try to use the follwoing code, I only get 1 subcategory/product from each category being displayed in my PHP page even though I have 100s of products under each category!
This what i tried:
<?php
$subcategories="";
$sql3="SELECT products.di_cat, products.url, GROUP_CONCAT(products.di_name) as di_name
FROM products LEFT JOIN category ON products.di_cat=category.names
GROUP BY products.di_cat";
$query3 = mysqli_query($db_conx, $sql3);
$existCount3 = mysqli_num_rows($query3);
if ($existCount3!=0) {
while($row3 = mysqli_fetch_array($query3, MYSQLI_ASSOC)){
$make_names = $row3["di_cat"];
$make_model = $row3["di_name"];
$make_url = $row3["url"];
$subcategories = explode(",",$make_url);
print '<div class="col-md-3">
<span class="mega-menu-sub-title">'.$make_names.'</span>
<ul class="sub-menu">
<li>
<ul class="sub-menu">';
foreach($subcategories as $sub){
print '<li>'.$sub.'</li>';
}
print '</ul></li></ul></div>';
}
}
?>
Can someone please advice on this issue?
Any help would be appreciated.

navigation list is duplicating

i was given help previously on how to join multiple tables together to get this navigation list to work, as you can see i have done this, but now i am trying to output the navigation in my list, but it is duplicating the top and bottom categories based on how many products are in those categories: this is previous link that shows my table setup:
Joining 2 tables with foreign key id
Here is my code trying to echo out the navigation correctly.
try
{
$result = $pdo->query('SELECT product.*, bottom_category.bottom_name, top_category.top_name
FROM product
INNER JOIN bottom_category ON bottom_category.id = product.bottom_category_id
INNER JOIN top_category ON top_category.id = bottom_category.top_category_id
ORDER BY top_category.id,bottom_category.id');
} // end try
catch (PDOException $e)
{
echo 'There was a error fetching the products.' . $e->getMessage();
exit();
} // end catch
$products = array();
foreach ($result as $row)
{
$products[] = array('top_name' => $row['top_name'],
'bottom_name' => $row['bottom_name']);
}
?>
<div class="sidebar">
<h4 class="sidebar-header">Select Products</h4>
<form class="nav-search-form">
<input type="search" name="search" placeholder="Search products">
</form>
<nav class="sidebar-links">
<ul>
<li><a id="red" href="/semtronics/index.php">New Products</a></li>
<?php
foreach ($products as $product):
?>
<li><?php echo htmlspecialchars($product['top_name']);?>
<ul>
<li><?php echo htmlspecialchars($product['bottom_name']);?></li>
</ul>
</li>
<?php endforeach; ?>
</ul>
</nav>
</div><!-- sidebar -->
Now it all works the only problem is it is duplicating the navigation list based on how many products are linked to that category.
I think you need another solution for this task.
You don't need product here
Query what you need is:
select bottom_category.name as bottom_name, top_category.name as top_name
from bottom_category
inner join top_category on top_category.id = bottom_category.top_category_id
order by top_category.id, bottom_category.id
I was thinking that you need something from product table in your code, but if no - use SQL query above.
Or you need data from product table ?
If you need from product you can run
select bottom_category.name as bottom_name, top_category.name as top_name
from product
inner join bottom_category on bottom_category.id = product.bottom_category_id
inner join top_category on top_category.id = bottom_category.top_category_id
group by product.bottom_category_id
order by top_category.id, bottom_category.id
But be careful, you don't know which row from product would be used in this case

PHP PDO fetch and foreach - I'm not getting the first column

This is my first post, so I'm just getting to know how the community works so I can be helpful too, later on...
I have an index.php and db.php for testing PDO in a very small and simple app, in the first one goes the html and the second the database connection.
index.php
<h1><?php echo $fjoin_bookname; ?></h1>
<?php foreach($join as $j): ?>
<tr>
<td>
<?php echo 'Page: '. $j['pageNumber']; ?>
</td>
<td>
<?php echo $j['pageNote']; ?>
</td>
</tr>
<?php endforeach; ?>
db.php
//get books and pages Join
$query='SELECT *
FROM books
INNER JOIN pages
ON books.bookID = pages.bookID
ORDER BY pageNumber ASC';
$join = $db->query($query);
$fjoin = $join->fetch();
$fjoin_bookname = $fjoin['bookName'];
It is an app that gets page numbers with a corresponding note from a book, this will help to keep track of several books while on different devices.
Problem:
I'm not getting the first row from the 'pages' table.
It was working fine until I inserted the fetch method
$fjoin = $join->fetch();
$fjoin_bookname = $fjoin['bookName'];
Question
Would anyone be so kind to help me work this out?
When you do a call of
$join->fetch()
it returns item from current position and move cursor to the next one.
You can fetch all elements to a var and then get fjoin_bookname from the first element:
db.php
//get books and pages Join
$query='SELECT *
FROM books
INNER JOIN pages
ON books.bookID = pages.bookID
ORDER BY pageNumber ASC';
$statement = $db->query($query);
$join = $statement->fetchAll();
$fjoin = $join[0];
$fjoin_bookname = $fjoin['bookName'];

How do i GROUP BY or DISTINCT inside array?

I have searched high and low and cant find a similar issue to what i have.
I am a beginner so please forgive my clunky query structure.
I am trying to ( have attached screen grab below of output ):
Query the photos table to get the id based on category id and also start,limit because of pagination.
Query the photos tagged table based on the photo id i just got from the first query.
But my problem is that i cant group the tags, some photos have the same tag name. And the output just shows all the tags for each photo. I want restaurant to show only once etc...
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id']." GROUP BY tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($rowTagged = mysql_fetch_array($resultTagged)) {
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php }} ?>
the above query is producing:
bar,cappucino,coffee,coffee machine,restaurant,bar,cappucino,coffee,coffee machine,restaurant,bar,coffee,restaurant,bar,coffee,coffee machine
restaurant,bar,cappucino,coffee,restaurant
what i need to show is:
bar,cappucino,coffee,coffee machine,restaurant
If anyone could help i would greatly appreciate it.
Thank you in advance.
John
My new code is
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged);
$tagged = $rowTagged['tag_name'];
?>
<li><a href="#"><?php echo $tagged; ?></li>
<?php } ?>
I now get this: ( So i am close arent i? )
----------
cappucino
restaurant
bar
coffee machine
restaurant
coffee
coffee
restaurant
restaurant
restaurant
coffee
coffee
restaurant
restaurant
coffee machine
restaurant
coffee
I wonder if the spaces are something? i got that from copy and paste...
Any further help would be appreciated :-)
You should first perform a join between your photos and tags table, and THEN select the distinct tags.
I believe this query will let the database do all the work for you:
SELECT DISTINCT tag_name
FROM (SELECT file_id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) t1
LEFT JOIN photoTagged ON t1.id = photoTagged.file_id
You can also sort the tags in the database (ORDER BY tag_name).
Haven't tried it myself, so maybe the syntax is a bit off. But the idea should work.
distinct doesnt work if you are only getting one record at a time, so put the data in a PHP array and then use array_unique, which is PHPs way to do distinct
<?php
// Get the file ideez and dont go beyond pagination start,limit eg:30,10
$queryFile = "SELECT id FROM $tableName WHERE cat_id=".$fileID." LIMIT $start, $limit";
$resultFile = mysql_query($queryFile);
while ($rowFile = mysql_fetch_array($resultFile)) {
// Get the tag names based on the file ideez retrived from the above query
$queryTagged = "SELECT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'];
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
$rowTagged = mysql_fetch_array($resultTagged)
$tagged[] = $rowTagged['tag_name'];
}
// Let PHP do the work.
$tagged=array_unique($tagged);
while (list(,$val) = each($tagged)) {
echo "<li><a href="#">$val</li>
}
?>
you need to do a sub-query to dodge the pagination problems with the photos. If you wish the selected tags to be a subset of the photos found in your first query, then you will need to do the following.
<?php
$queryTagged = "SELECT TAG.tag_name, count(TAG.tag_name) AS num FROM photoTagged as TAG JOIN (SELECT id FROM $tableName WHERE cat_id=$fileID LIMIT $start, $limit) as PHOTO ON (PHOTO.id = TAG.file_id) GROUP BY TAG.tag_name";
$resultTagged = mysql_query($queryTagged) or die(mysql_error());
while ($tagged = mysql_fetch_assoc($resultTagged)) {
echo "<li id="'.$tagged['TAG.tag_name'].'"><a href="#">".$tagged['TAG.tag_name']." (".$tagged['TAG.num'].")</li>";
}
?>
This way you will have two queries, on for finding the photos, and one for finding the tags for the photos on that page. This technically takes a little longer as MySQL has to load the query into a temporary table, but it should work fine.
SELECT DISTINCT tag_name FROM photoTagged WHERE file_id=".$rowFile['id'] ?

Categories