PHP and MySql, join three tables and reading - php

I have 3 database tables, products, categories, and assignment
All three tables have a unique id.
The third table assignment, associates product IDs with the category IDs. An example:
products:
---------------------
| name | id |
---------------------
| white shirt | 234 |
| black pants | 0u2 |
categories:
---------------------
| name | id |
---------------------
| shirts | x23 |
| pants | 28x |
assignment:
------------------------
| catId | itemId | id |
------------------------
| x23 | 234 | 892 |
| 28x | 0u2 | 561 |
I want to create a list. An example:
<items>
<cats>shirts</cats>
<item>white shirt</item>
<cats>pants</cats>
<item>black pants</item>
</items>
It is important that the first category name and then products are listed in the category.
Sql:
select assignment.itemId, assignment.catId from assignment
left join categories
on categories.id = assignment.catId
where categories.active = '1'
My SQL query works fine. The problem is in a while loop to provide list correctly together.
PHP while loop:
if ($res != false && $res->count() > 0) {
$i = 0;
$html = '<items>';
while (!$res->EOF) {
$categories = $res->fields[1];
$html .= '<cats>'.$categories->title.'</cats>';
$products = $res->fields[0];
$html .= '<item>'.$products->title.'</item>';
$i++;
}
$html .= '</items>';
}
In a while loop I can read products fields[0] and categories fields[1], but I can't make a list like I want.
my result is as follows:
shirts
pants
white shirt
black pants
do you have any solutions for me?
thank you!

Related

Two unrelated tables with match and against functions

How do I combine two unrelated tables into one SQL select statement request. However, both tables need to have the Match and Against functions for full text search. I'm getting a blank response and when I do a single table SQL match and against request it works fine but not when I do two tables.
Table One: transport - only id is a primary key integer auto_increment but the rest are varchar
+----+---------+-----------+--------------+
| id | title | type | tags |
+----+---------+-----------+--------------+
| 1 | triumph | motorbike | sport, black |
+----+---------+-----------+--------------+
| 2 | bmw | car | hatchback |
+----+---------+-----------+--------------+
Table Two: automobile - - only id is a primary key integer auto_increment but the rest are varchar
+----+-----------+-----------+------------+---------+
| id | name | kind | link | listed |
+----+-----------+-----------+------------+---------+
| 1 | suzuki | motorbike | /bike/new/ | green |
+----+-----------+-----------+------------+---------+
| 2 | volkwagan | car | /car/new/ | limited |
+----+-----------+-----------+------------+---------+
I need it to print out something like this (just a note, not sure how I would need id - perhaps two columns id_automobile and id_transport to references both above tables)
+----+-----------+-----------+------------+--------------+
| id | title | type | link | tags |
+----+-----------+-----------+------------+--------------+
| 1 | suzuki | motorbike | /bike/new/ | green |
+----+-----------+-----------+------------+--------------+
| 2 | triumph | motorbike | | sport, black |
+----+-----------+-----------+------------+--------------+
| 3 | bmw | car | | hatchback |
+----+-----------+-----------+------------+--------------+
| 4 | volkwagan | car | /car/new/ | limited |
+----+-----------+-----------+------------+--------------+
My failed attempt:
<table>
<tr>
<th>Title</th>
<th>Type</th>
<th>Link</th>
<th>Tags</th>
</tr>
if(isset($_GET['search'])) {
$search = $_GET['search'];
} else {
$search = '';
}
$sql = "SELECT * FROM `transport` WHERE MATCH(title, tags) AGAINST('".$search."') CROSS JOIN `automobile` WHERE MATCH(name, listed) AGAINST('".$search."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row["title"]."</td><td>".$row["type"]."</td><td>".$row["link"]."</td><td>".$row["tags"]."</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
</table>
I would appreciate any help please
A UNION clause should give you the results that you need.
Just make sure that bost SELECTs, combined with UNION, have similar column sets. You can use AS to define aliases.
Something like this:
SELECT title, type, '' AS link, tags
WHERE MATCH(title, tags) AGAINST('...')
FROM transport
UNION
SELECT name AS title, kind AS type, link, listed AS tags
FROM automobile
WHERE MATCH(title, kind) AGAINST('...')

Display categories being supplied by a supplier

I have my 2 tables : tbl_supplier & tbl_categories
I want to display all the categories being supplied by a supplier in a dropdown select option in php html
Example:
Supplier1 > Category1, Category2, Category3
Supplier2 > Category2, Category4
You need a third table with one row per Supplier/Category combination:
Supplier
| id | name |
|----|------|
| 1 | John |
| 2 | Ana |
| 3 | Dan |
Category
| id | name |
|----|------------|
| 1 | category 1 |
| 2 | category 2 |
| 3 | category 3 |
Supplier_categories
| id | Supplier_id | categ_id |
|----|-------------|----------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
| 4 | 2 | 3 |
Then you can retrieve a list of each supplier categories by doing INNER JOIN to the three tables and putting conditions like this:
SELECT Supplier.id, Category.name
FROM Supplier
INNER JOIN Supplier_categories
on Supplier_categories.Supplier_id = Supplier.id
INNER JOIN Category
ON Category.id = Supplier_categories.categ_id
WHERE Supplier.id = 1 //(for example)
Assuming your tbl_supplier contains a sid primary key, and then that key is present in tbl_categories to keep track of suppliers, and cat is the column to hold category name, the query would be like this:
Select c.cat from tbl_supplier as t, tbl_categories as c where t.sid=c.sid and t.sid='supplier-1'
Example for Supplier 1:
<label>Supplier1:</label>
<select name="supplier-1">
<option>All</option>
<?php
$query = mysqli_query($conn,"Select c.cat from tbl_supplier as t, tbl_categories as c where t.sid=c.sid and t.sid='supplier-1'");
while($row=mysqli_fetch_array($query)){
echo "<option>".$row['cat']."</option>";
}
?>
</select>
However, if you would like to dynamically add multiple suppliers dropdowns then you would need to write a more complex query.
Hope I helped!

how to show multiple record in one table row

How to show multiple record in one table row ?
I'm not good explain using words, so i'll use an example :
Work No. | Product No. | Product Name | Qty | Item No. | Item Name | Qty |
--------------------------------------------------------------------------
W00001 | P0000001 | Product_1 | 6 | I000001 | Item_1 | 2 |
| | | | I000002 | Item_2 | 2 |
| | | | I000003 | Item_3 | 2 |
--------------------------------------------------------------------------
Total : 6 |
--------------------------------------------------------------------------
W00002 | P0000002 | Product_2 | 7 | I000001 | Item_1 | 3 |
| | | | I000004 | Item_4 | 4 |
--------------------------------------------------------------------------
Total : 7 |
--------------------------------------------------------------------------
as you can see, product is made from multiple items. So far, i can make more less like example above but my question is how to display item like example above. I want to show items in one row. How to show that using php ?
If you already have 2 tables: one for products and one for items you simply have to loop throw the products one and for each product get all the items needed for that product and display there.
Your code needs to look something like this:
$products = get_products_from_db(); //How you normal get products from db.
foreach($products as $product) {
$items = get_items_by_product_from_db($product['id']); //get from db all items for a product.
//foreach product we will need a new row.
echo '<tr>';
echo "<td>{$product['work_no']}</td>"; //and all the normal cells like this.
//for item no. we will create a cell and inside it we will foreach items.
echo "<td>";
foreach($items as $item) {
echo $item['item_no'] . '<br/>';//Or how it's called in db.
}
echo "</td>";
//Exact the same with name and quantity.
//For quantity also keep a counter so you can display the total
echo '</tr>';
//After this row create a new tr to display the total. I think you know how to do this.
}

PHP MYSQL INNER JOIN to JSON

I had a two table,
First one : table product table product
| id | name | code |
| 1 | blouse | AB1 |
| 2 | jeans | BA2 |
| 3 | dress | C61 |
and the second table color table color
| id_product | colors | amount |
| 1 | blue | 50 |
| 1 | red | 40 |
| 1 | yellow| 10 |
| 2 | white | 15 |
| 2 | blue | 60 |
| 3 | purple| 110 |
Query : my query php
.../blabla
SELECT product.id, product.name, product.code,color.id_product, color.colors, color.amount
FROM product
INNER JOIN color
ON product.id = color.id_product limit 1
while($query)) {
$var[] = $query;
}
echo '{"status":'. json_encode($var).'}';
OUTPUT :
{
"status":{
"1":{
"id":"1",
"code":"blouse",
"id_product":"1",
"colors":"blue",
"amount":"50",
}
}
}
what i want JSON like this :
{
"status":{
"1":{
"id":"1",
"code":"blouse",
"id_product":"1",
"colors":"blue",
"amount":"50",
"id_product":"1",
"colors":"red",
"amount":"40",
"id_product":"1",
"colors":"yellow",
"amount":"10",
}
}
}
Need color into one array json, is that possible?
So you should probably use group_concat to get them into a list and then use PHP to explode the list before encoding to json.
SQL Fiddle Here
http://sqlfiddle.com/#!9/ba3b8/3
SELECT product.id, product.name, product.code,
color.id_product, color.colors, color.amount,
group_concat(color.colors) as clist,
group_concat(color.amount) as alist
from product, color
where product.id = color.id_product
group by color.id_product
Then in your PHP you would need to loop through the results, using explode to convert the list to an array and inserting the data into the results as needed PRIOR to using json_encode();
You should use this query:
SELECT product.id, product.name, product.code
color.id_product, color.colors, color.amount
from product
INNER JOIN color
ON product.id = color.id_product
where product.id=1
LIMITwill give you exactly one record.

MySQLi join and display details differently from 2 tables

Hello I have actually asked a similar question a while ago but only just realized I did not get an answer that solves my problem.
I have 2 tables in a MySQL DB, that are connected by the same main id, the following code is just a simplified example of the original code:
table1:
+-----------------------+
| main_id | name | type |
+-----------------------+
table2:
+----------------------------------------+
| main_id | secondary_id | color | price |
+----------------------------------------+
the result I want to achieve is to get every row of table 1, and under each one list all the linked by main id rows from table2, for example:
table1 rows:
+-------------------+
| 1 | name1 | type1 |
| 2 | name2 | type2 |
| 3 | name3 | type3 |
+-------------------+
table2 rows:
+----+------+----------+------+
| 1 | 23 | red | 500 |
| 1 | 24 | blue | 600 |
| 1 | 25 | green | 700 |
| 2 | 26 | pink | 400 |
| 2 | 27 | purple | 200 |
| 3 | 28 | white | 100 |
+----+------+----------+------+
result in display:
<h1 class="1">name1, type1</h1>
<div class="23">red,500</div>
<div class="23">red,500</div>
<div class="24">green,700</div>
<h1 class="2">name2, type2</h1>
<div class="25">pink,400</div>
<div class="26">purple,200</div>
And so on...I was using a while loop inside a while loop which wasn't giving me the required result, then I was advised to use MySQL JOIN, but when I do I get all values of the matching ids and cant display the headings only once and then list the related results under it, can someone please help me?
this is a simplified query i was using:
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
//Get details and display
}
}
}
In your description, you use main_id, but in the code you use just id. Not sure which you're really using here - you will have to edit the code below to match your actual column names. If the database column name is actually main_id, then for instance the line with $id = $rows['id'] would have to be $rows['main_id']. Or it won't work.
while($rows = $headings->fetch_array(MYSQLI_BOTH))
{
echo '<h1 class="'.$rows['id'].'">'.$rows['name1'].', '.$rows['type'].'</h1>';
$id = $rows['id'];
$conts_q = $mysqli->query("SELECT * FROM `table2` WHERE id='$id'");
$conts_numr = $conts_q->num_rows;
if($conts_numr==0)
{
//Display empty
}
else
{
while($row2 = $conts_q->fetch_array(MYSQLI_BOTH))
{
if ($row2['id'] == $id) {
echo '<div class="'.$row2['secondary_id'].'">'.$row2['color'].', '.$row2['price'].'</div>';
}
}//while
}//else
}//while

Categories