Ok folks. I have a Table categories with id, categoryname.
categories has: id=1 categoryname = batteries, id=2 categoryname = flashes, id=3 categoryname glasses.
The Second table is users. Users have id, user_eimal, my_choices.
Every user has store into my_choices the category name that wants to appear.
So for example user George with user_email xxxxx#xxx.com has store in my_choices: batteries,glasses
Now i want to bring up records from table products where categoryname is the values that user george has stored into my_choices.
Products has id, p_title, categoryname
for example i want to:
<?php
$usenmail = $_SESSION['SESS_EMAYL_NAME'];
$q1 = "SELECT * FROM categories WHERE id = '$id'";
$q2 = mysql_query($q1, $connectiondb) or die(mysql_error());
$results = mysql_fetch_assoc($q2);
$my_choices = $results['my_choices']; //That means $my_choices = batteries,glasses
//Now i want to select fom my table poducts only the categories (batteries,glasses)that user has store.
$trt = mysql_query ("select * from products where categoryname = batteries,glasses");
while($apst = mysql_fetch_assoc($trt)) {
echo '<div style="color: #000; float: left;">Productname: '.$['apst'].'</div>';
echo '<br>';
}
?>
You want to use a join table so you can have a many-to-many relationship. Your current structure is better suited to each user only having ONE choice.
What you want are three tables:
Users (userID, user_name, user_email)
Categories (categoryID, category_name)
Users_Categories (userID, categoryID)
So to use your example, your three tables would look like this (if anyone knows a better way to demonstrate SQL tables on here, please let me know):
Users
userID: 1 | user_name: George | user_email: george#example.com
Categories
categoryID: 1 | category_name: batteries
categoryID: 2 | category_name= flashes
categoryID: 3 | category_nameglasses.
Users_Categories
userID: 1 | categoryID: 1
userID: 1 | categoryID: 3
You would then use a select statement with a join clause to get George and his categories:
SELECT
user_name,
category_name
FROM
Users
LEFT JOIN Users_Categories USING (userID)
LEFT JOIN Categories USING (categoryID)
WHERE
userID = 1
This would return two rows in the result:
George, Batteries
George, Glasses
Depending on what you want to do with that data, it may be better to also select the userID.
If you want a query that will only return one row with all of the information, it gets a little trickier. You have to use the GROUP BY functionality. That would look like this:
SELECT
user_name,
GROUP_CONCAT (category_name ',')
FROM
Users
LEFT JOIN Users_Categories USING (userID)
LEFT JOIN Categories USING (categoryID)
GROUP BY
userID
WHERE
userID = 1
For your final question about products, you would follow the same logic with more joins. Your Products table wants to have a productID, product_name, and categoryID.
$trt = mysql_query ("select * from products where categoryname = 'batteries' OR categoryname = 'glasses'");
Use explode function
$array = explode(','$my_choices);
now array[0] and array[1] have the 2 values. then use
$result = mysql_query ("select * from products where categoryname = '".$array[0]."' OR categoryname = '".$array[1]."'");
In your case use select statement as,
select * from products where categoryname in ( 'batteries','glasses');
ie,
//add quotes to category names (if ids you dont neeed these 2 lines)
$cats=explode(',',$my_choices);
$strcats = "'" . join("', '", $cats) . "'";
$trt = mysql_query ("select * from products where categoryname in ($strcats));
My suggestion to use category ids instead of category names.
Related
I know this may be a stupid question but I am not very experienced with SQL Joins and I don't want to do it without fully knowing that it is the right thing to do.
I have created a recipe site which have different categories like bread, biscuits, cake etc. these are all in the category table of the database. I have recipes in the recipe table.
The problem I am facing is, on the category page, since each category has its own ID I created one page where each categories redirect to and used this code
<a href="index.php?p=selected&id=<?php echo $recipe['cat_id']; ?>">
This one page features different categories based on the ID, the id is changed in the url so for the bread category it would look like this:
index.php?p=selected&id=1
So, since there is one page for each category I want it to display the recipes, I used this code:
$query = "SELECT * FROM recipes ORDER BY recipe_id ASC";
but this displays every recipe in the database, what I want is for it to display the recipe based on the category it is in like below:
$query = "SELECT * FROM recipes WHERE cat_id = :id ORDER BY recipe_id ASC";
The cat_id is part of the category table, so do I need to join this table to the recipe table to make it work?
Be sure to tell me if I have missed something,
Thank you for your time.
yes you have missed something
must add column cat_id in recipes table which equal cat_id in category table
when you add item in recipes table
and then it simple
$query = "SELECT * FROM recipes
WHERE recipes.cat_id = :id";
or
$id = intval($_GET['id']);
$query = "SELECT * FROM recipes
WHERE recipes.cat_id = $id";
If one recipe one category then,
SELECT * FROM recipes inner join category
on category.id=recipe.cat_id
where cat_id = :id ORDER BY recipe_id ASC";
If one cateory many recipes then
SELECT * FROM recipes leftjoin category
on category.id=recipe.cat_id
where cat_id = :id ORDER BY recipe_id ASC";
I have a problem
not displayed the name for id
data base structure for category_list
id name
1 php
2 mysql
... ...
10 html
and data base structure for entries
category_id
8
5
for the results i have this code, this script displays the ID
as a result it shows 2 , but i want the following to be displayed: mysql
but I want to show name for this ID , instead of ID
We need to use a join query to get the category name for given id, e.g.:
select c.name
from category_list c join entries e on c.id = e.category_id
where category_id = ?
Presumably your database query is something like this:
SELECT category_id FROM some_table
Thus, you're only selecting the ID, not the Name. You can include the Name by joining the other table. Something like this:
SELECT
category_id,
name
FROM
some_table
INNER JOIN category_list
ON some_table.category_id = category_list.id
Then your results would also include the Name value, which you could output to the page:
echo $rows['name']
Run a second query pulling name from category_list like so:
$sql = "SELECT name FROM category_list WHERE id = '$rows['category_id']';";
$result = mysqli_query($conn, $sql);
$category_name = mysqli_fetch_assoc($result);
echo $category_name['name'];
It would however be better to use a JOIN as others like David have pointed out.
Hi everyone this is my first question here and i'll be very grateful if you could help me.
I have a table like this in mysql
//table items
id | item_name | description | link | category_id | is_active
And i have another table like this
//table categories
id category_name | cat_description | is_active
I want to get all the data in category_name and get all the content from item_name if is_active column is on, and also if category is_active column is on.
I was trying to make a function that would retrieve all that data with html content and just if certain conditions are true.
My function is something like this:
function getCatAndItems(){
include "conn.php";
$petition = mysqli_query($conn,"SELECT * FROM items,categories WHERE is_active=1");
while ($row = mysqli_fetch_array($petition)) {
$filename = $row['nombre'];
$url = $row['url_document'];
echo "<a href=../docs/files/$url'><li> ".$filename."</li></a>";
}
}
My goal is to bring the categories and if the categories are active and if the items table in the category_id is the same as the category id and is_active it will bring me also the data in the items table that share the same number.
I hope you understand me and hope you could help me, thank's
You can get using JOIN
SELECT items.name, items.description, items.link, categories.category_name, categories.cat_description
FROM categories
JOIN items
ON categories.id = items.category_id
WHERE categories.is_active = 1
AND items.is_active = 1;
Here is your query :
select i.id,i.item_name,i.description,i.link,i.category_id,i.is_active,c.category_name
from items as i left join categories as c on i.category_id=c.id where
i.is_active=1 and c.is_active=1;
A simple inner join between these two tables would do the job done.
SELECT
items.name,
items.description,
items.link,
categories.category_name,
categories.cat_description
FROM categories
INNER JOIN items ON categories.id = items.category_id
WHERE categories.is_active = 1
AND items.is_active = 1
Like below image I have two tables, now I want to get all columns from Restaurant table depending on cat column, and number of records from Foods table that have that Restaurant id.
example : (to get 1,test from Restaurant table and 3 from Foods table).
$sql = "select * from Restaurant,Foods where cat=6..." ;
updated :
$sql = "r.*,(SELECT COUNT(*) FROM restaurant_foods WHERE restaurant_id = r.id)
foods_count FROM restaurant r WHERE r.cats LIKE '%,$cat,%' limit $start,$end"
That should do the job:
SELECT r.*,
(SELECT Count(*)
FROM Foods
WHERE restaurnat_id = r.id) foods_count
FROM Restaurant r
WHERE r.cat = 6
Lets say I have 3 columns and 3 rows, the first column is for ID, the second is names, third is votes. like:
+----+------+-------+
| id | name | votes |
+----+------+-------+
| 1 | bob | 7 |
| 2 | jill | 2 |
| 3 | jake | 9 |
+----+------+-------+
How can I have PHP compare the values in the votes field and sort it by whichever had the highest number, and attach a rank of #1,2,3, etc. depending on how many votes it had?
Each value will be displayed on a separate page. For example, if I went to 'bob's page' with the ID of 1, I would need it to display '#2 bob' since he would be ranked 2nd by votes.
You can make a separate column rank and update it by running the following code whenever your vote changes. This method will make you more efficient as in this you wont be sorting the table again and again when user visits his page:
$q = "select * from tableName order by votes DESC";
$a = mysql_query($q);
$count = 1;
while($arr = mysql_fetch_array($a){
$up = "update tableName set(rank) VALUES($count) WHERE name=$arr['name']";
$aq = mysql_query($up);
$count++;
}
Now on individual pages, you can just retrieve the rank value and show
$user = "Bob";
$q = "select rank from tableName where name=$user";
$a = mysql_query($q);
$arr = mysql_fetch_array($a);
echo $arr[0];
Also this(a slight modification in other answer) should work for you :-
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) as P ORDER BY vote DESC
You could read the values returned by your query into an array and then sort said array.
You want a SELECT query doing an ORDER BY votes, and create a special variable to handle the rank of a row:
SELECT #rownum:=#rownum+1 AS rank, name, vote FROM table, (SELECT #rownum:=0) ORDER BY vote DESC
This query should let you fetch an array with the rank, name, and number of votes of each person of your table.
Alternatively, you can just sort by vote, and add the rank value yourself with PHP.
You can use the MySQL 'ORDER BY' and display those ranks using PHP:
For this example:
<?php
//connection
//DB selection
$query = "SELECT * FROM table_votes ORDER BY votes DESC";
$result = mysql_query($query);
for(int $i=1; $row = mysql_fetch_array($result);i++)
{
echo "#".$i.$row['name']."<br/>";
}
?>