This is a multi-part question. My database looks like this:
USERS
-id
-fname
-lname
COMPANIES
-id
-name
-type
PRODUCTS
-id
-product
-restaurant (foreign key to companies id)
-vendor (foreign key to companies id)
-user (foreign key to users id)
-transaction_date
Is this a good way to set up the database? I was thinking of having separate tables for restaurants and vendors but wanted them to use the same login page and rather than have to worry about UNION queries, I just select them by type. They see different information upon login so I have an if statement that says if type = r, show this else show that. Best way?
The second issue comes up when I want to show the information upon login. Say a vendor logs in, they will see a list of all the records that match their vendor id. However, I am seeing too many records because of my nested loop. For example, the table looks like this:
Date--Product--Restaurant--User
I am using this query:
$sql = mysql_query("SELECT products.*, companies.name, CONCAT_WS(' ', users.fname, users.lname) AS fullname FROM products INNER JOIN companies ON products.vendor = companies.id INNER JOIN users ON products.user = users.id WHERE company='$id' AND companies.type='$type'") or die(mysql_error());
$num=mysql_num_rows($sql);
$sql1 = mysql_query("SELECT products.restaurant, companies.name AS cname FROM products INNER JOIN companies ON products.restaurant = companies.id") or die(mysql_error());
$num1=mysql_num_rows($sql1);
$i = 0;
while ($i < $num) {
$j = 0;
while ($j < $num) {
$d = mysql_result($sql,$i,"transaction_date");
$p = mysql_result($sql,$i,"product");
$r = mysql_result($sql1,$j,"cname");
$u = mysql_result($sql,$i,"fullname");
<td><?php echo $d; ?></td>
<td><?php echo $p; ?></td>
<td><?php echo $r; ?></td>
<td><?php echo $u; ?></td>
$j++; }
$i++; }
$id and $type are session created values upon login. There are 4 example records currently in the table. Rather than showing just 4, it shows 16 because the values of $num and $num1 are both 4 and $num is looping $num1 four times.
How can I fix this problem and just show the 4 records?
Thank you for your help. Let me know if you need any clarification on any part.
Your database set-up may need a little rethink.
The reason I think this is that you need to know which company each user is in and you cannot have this within the products table as you have.
I would consider adding the foreign key to the users table like so (assuming one user has one company and one company has many users). I have also made some other suggestions, something like the below:
users
- id
- company_id
- first_name
- last_name
companies
- id
- name
- company_type_id
company_types
- id
- type
products
- id
- product_name
- company_id
transactions
- id
- user_id
- product_id
- transaction_date
they will see a list of all the records that match their vendor
Now you will notice I removed the vendor id from the above tables - This is because the vendor id is the same as the company id. There is no point having two separate relationship id's for the same thing (correct me if I'm mistaken)
So with the above changes we can list these records easily, as so:
<?php
$db = new PDO(/**Connection info here**/);
$stmt = $db->prepare("
SELECT
a.id AS product_id,
a.product_name
FROM
products AS a
INNER JOIN
companies AS b ON b.id = a.company_id
INNER JOIN
company_types AS c ON c.id = b.type_id
WHERE
b.id = :company AND c.id = :companyType
");
$stmt->bindParam(":company", $usersCompanyIdHere, PDO::PARAM_INT);
$stmt->bindParam(":companyType", $usersCompanyTypeHere, PDO::PARAM_INT);
$data = $stmt->execute();
while ($row = $data->fetch()) {
/** List of all the products for given company id**/
}
?>
I have changed you code to use PDO, I don't want to overload you with info here but I cannot stress enough the benefits of using the PDO over native mysql_* functions - Do a Google search, I can see lots of useful and relevant information in the top 10 results.
Related
I have a problem with this MySQL Statment. So basicly i have a table called games and i want to
display this table on my website. Table games has Foregin Keys like developer_id,
publisher_id, categorie_id, platform1_id, platform2_id, platform3_id, platform4_id, platform5_id.
I have 5 of platform because in Table platforms i have 5 records (PC, PS4, XB1, SWITCH, MOBILE). (If you guys know any better and easier solution to these platforms pls tell me.)
So now my output on my website works but for example instead of showing developer name it shows
it's ID. I know i have to INNER JOIN them and i probbably can INNER JOIN all foregin keys but the
platform one. Because i dont know how to INNER JOIN if you have more then one FK from one table.
If you need more info tell me. I will also include picture of my DB and my PHP code where i SELECT from table games.
$query = "SELECT * FROM games WHERE id = $id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>'.$row['developer_id'].'</td>';
echo '<td>'.$row['publisher_id'].'</td>';
echo '<td>'.$row['categorie_id'].'</td>';
echo '<td>'.$row['platform1_id'].'</td>';
echo '<td>'.$row['platform2_id'].'</td>';
echo '<td>'.$row['platform3_id'].'</td>';
echo '<td>'.$row['platform4_id'].'</td>';
echo '<td>'.$row['platform5_id'].'</td>';
echo '<td>'.$row['game_name'].'</td>';
echo '<td>'.$row['relese_date'].'</td>';
$intro = $row['introduction'];
$desc = $row['description'];
echo '<td>'.$row['rating'].'</td>';
echo '</tr>';
}
Picture of my DataBase
SELECT games.game_name, games.relese_date, games.introduction, games.rating, games.description, dev.name as developer, pub.name as publisher, (SELECT * FROM platforms WHERE platforms.id in (games.platform1_id,games.platform2_id,games.platform3_id,games.platform4_id,games.platform5_id)) as plats
FROM games
INNER JOIN developers AS dev ON dev.id = games.developer_id
INNER JOIN publishers AS pub ON pub.id = games.publisher_id
WHERE games.id = $id
Keep in mind that the platforms will be listed as a collection under the property plats, and each of those items will be an object of properties as.
E.X.
return object=>
developer_id
publisher_id
categorie_id
plats => [
platform1_id=>name,
platform2_id=>name,
platform3_id=>name,
platform4_id=>name,
platform5_id=>name
]
game_name
relese_date
introduction
description
rating
Thanks in advance for any time you spend on my question.
I am trying to display data in a way that will display the manufacturer as a name instead of a number.
Basically when they store the data they choose a manufacturer from a drop down which is generated from a table.. IE Trogues = 1 so products stores the #1 so I know that any beer is associated with trogues is 1. Now I want to display the data but instead of having a 1 I would like to have Trogues be displayed. Where you see manufacturer in the echo code below..
I am not understanding the process logic here..
error_reporting(E_ALL);
ini_set('display_errors', 1);
$sql = "SELECT * FROM products
LEFT JOIN manufacturer
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
<div class=reportclientproduct>".$row['manufacturer']." - <a href=".$row['website']." target=_blank>".$row['product']."</a></div>";
}
Have you tried the query like this:
$sql = "SELECT man.id AS manufac, products.product AS prod FROM products
LEFT JOIN manufacturer as man
ON product.manufacturer = manufacturer.id
ORDER BY manufacturer.id, product.id";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "
".$row['manufac']." - ".$row['prod']."
";
}
Assuming that the table products had a column named manufacturer which holds the ID of the manufacturer, and that both tables have columns name ID which hold the ID of the table item.
Also the JOIN functions may vary based on the database you use. But the aforementioned method is for mysql.
$sql = "SELECT * FROM books LEFT JOIN users
ON books.readby=users.user_id WHERE users.email IS NOT NULL";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['readby']. " - read 10 books";
} //while ends
this is the code I have so far. I am trying to retrieve the number of books read by each user
and echo the results. echo the user_id and number of books he/she read
books table is like this : id - name - pages - readby
the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.
A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.
Edit The GROUP BY had been omitted...
SELECT
users.*,
usersread.numread
FROM
users
/* join all user details against count of books read */
LEFT JOIN (
/* Retrieve user_id (via readby) and count from the books table */
SELECT
readby,
COUNT(*) AS numread
FROM books
GROUP BY readby
) usersread ON users.user_id = usersread.readby
In your PHP then, you can retrieve $row['numread'] after fetching the result.
// Assuming you already executed the query above and checked errors...
while($row = mysql_fetch_array($result))
{
// don't know the contents of your users table, but assuming there's a
// users.name column I used 'name' here...
echo "{$row['name']} read {$row['numread']} books.";
}
You can use count() this way:
<?php
$count = mysql_fetch_array(mysql_query("SELECT COUNT(`user_id`) FROM books LEFT JOIN users ON books.readby=users.user_id WHERE users.email IS NOT NULL GROUP BY `user_id`"));
$count = $count[0];
?>
Hope this helps! :)
I just need help refining this script to give me the values from both tables joined on the ID.
Basically I want the ID from both tables and then be able to get the other values from both tables based on the IDs (if need be) and display them in a loop.
The code I have is below but won't work.
$select = myQ("SELECT * FROM users a WHERE EXISTS (SELECT 1 FROM `videos` b WHERE a.id = b.id GROUP BY b.id HAVING count(*) > 1) ");
$i=0;
while ($row = myF($select)) {
$resultsLoopArray[$i]["videos.id"] = $row["id"];
$resultsLoopArray[$i]["videos.vid"] = $row["vid"];
$resultsLoopArray[$i]["users.username"] = $row["username"];
$i++;
}
if (isset($resultsLoopArray)) {
$tpl->Loop("searchResultsLoop", $resultsLoopArray);
}
For now all I need is the username from the users table, the id and video id from the video table.
Can someone help by chance?
you question is bit confusing me..
As for my understanding I am posting this soultion..
If you have two tables users , videos then .
$sql = "SELECT users.username , videos.* from users, videos where users.user_id = videos.user_id";
this query will fetch all record from users and videos table where user id is present in videos tables ...
I am looking for a cleaner way to do this. My code works, but I know it can be better. I have three tables: one with a list of Category Groups, One with a list of categories that are linked to category groups, and one with a list of news stories that are linked to the categories.
I need to loop through all of the names of the Category Groups, followed by the names of the categories that are in the category groups, with the number of news stories in each category listed as well.
I have three tables: CategoryGroups, Categories, News.
I have a set of queries. The first queries all the rows from the CategoryGroups table:
$result = mysql_query( '
SELECT cat_group_id, cat_group_name FROM CategoryGroups
' );
The second query is inside the looped results of the first query and finds all the categories that have a news item and are linked to a specific category group:
<?php
while( $row = mysql_fetch_assoc( $result ) ){
$id = $row['cat_group_id'];
$name = $row['cat_group_name'];
echo "<h3>$name</h3>";
$sql = mysql_query("
SELECT category_id, title FROM `Categories`
WHERE cat_group_id = $id
AND category_id IN
(SELECT news.category_id FROM news)
");
while( $row = mysql_fetch_assoc($sql) ) {
$title = $row['title'];
$catid = $row['category_id'];
$numbers = mysql_query("
SELECT * FROM news
WHERE category_id =$catid"
);
$nums = mysql_num_rows($numbers);
echo "$title ($nums)<br/>\n";
}
?>
I would like to limit this to one or two queries, with efficiency in mind. I know this can be done, however I have not been successful in my attempts.
thanks.
Why not JOIN the tables?
SELECT cat_group_name, title, count(newsid)
FROM CatagoryGroups
INNER JOIN Categories ON cat_group_id
INNER JOIN News ON category_id
GROUP BY cat_group_name, title
looks like it should be close, if table news has a newsid column (it's gotta have SOME primary key, right? well, count that;-). With the obvious indexes the JOINs should be quite fast, and your PHP code can do whatever output formatting you may need from that.
I suggest you need to get a book on SQL, such as "SQL Queries for Mere Mortals."
$sql = mysql_query("
SELECT cg.cat_group_name, c.title, COUNT(n.category_id) AS NumNews
FROM `CategoryGroups` cg
JOIN `Categories` c USING (cat_group_id)
JOIN `News` n USING (category_id)
GROUP BY cg.cat_group_name, c.title");
Then loop over the result and output a new <h3> each time the cat_group_name is different from the previous row.