Count function() - php

I have these two table with some data sample in them. I would like to to pull out number of classifieds in each category. I gave it a try, and I got (2) in each one which is not correct. So hopefully someone will help me with this.
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`name` text COLLATE utf8_unicode_ci NOT NULL,
`subcategory_id` int(2) NOT NULL DEFAULT '0',
`parent_id` int(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=27 ;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `name`, `subcategory_id`, `parent_id`) VALUES
(1, 'Announcements', 0, 0),
(2, 'Employment', 0, 0),
(3, 'Items For Sale', 0, 0),
(4, 'Services', 0, 0),
(5, 'Garage Sales', 0, 0),
(6, 'Automobiles', 0, 0),
(7, 'Announcement1', 1, 1),
(8, 'Announcement2', 1, 1),
--
-- Table structure for table `classifieds`
--
CREATE TABLE IF NOT EXISTS `classifieds` (
`classified_id` int(255) NOT NULL AUTO_INCREMENT,
`title` text COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`category_id` int(10) NOT NULL,
`name` text COLLATE utf8_unicode_ci NOT NULL,
`authorized` int(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`adid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=177 ;
--
-- Dumping data for table `classifieds`
--
INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(1, 'Test Classified', 'Here is the First Test classified listing.', 1, 1);
INSERT INTO `classifieds` (`classified_id`, `title`, `description`, `category_id`, `name`, `authorized`) VALUES
(2, 'GMC For Sell', 'Looks like new 1979 GMC.', 6, 1);
here
$query = "SELECT category_id, COUNT(title) FROM classifieds GROUP BY category_id";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result)
$num_items_in_category = $row['COUNT(title)'];
echo "<><a href='category-".$row['id'].".php' >".$row['name'].$num_items_in_category."</a></li>";
Thanks

Change the SQL a bit, and loop through the results?
$query = "SELECT c.id, c.name,
COUNT(cl.category_id) AS num_items_in_category
FROM category_id c
LEFT JOIN aclassifieds cl ON cl.category_id=c.id
GROUP BY c.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "<li><a href='category-".$row['id'].".php' >".$row['name'].$row['num_items_in_category']."</."</a></li>";
}

Just in case someone else wants to benefit my this:
enter $query = "SELECT c.id, c.name,
COUNT(cl.title) AS num_items_in_category
FROM categories c
LEFT JOIN classifieds cl ON cl.category_id=c.id
GROUP BY c.id";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "".$row['name'].$row['num_items_in_category']."";
}
here
Thanks

Related

Multiple mysql query in CI

There I have some multiple query and want to execute in Codeigniter.
Below are the code I tried.
function seememberfilter($course,$n)
{
$this->load->database();
$sql = array();
$sql[] = "CREATE TEMPORARY TABLE temp1";
$sql[] = "select id,rand, name,lname, email,phone from `member` where course like ('%$course%')";
$sql[] = "CREATE TEMPORARY table temp2";
$sql[] = "select distinct t.id,t.rand, t.name,t.lname, t.email,t.phone, a.quest_id from temp1 t left join assignment a on t.rand= a.rand";
$sql[] = "CREATE TEMPORARY table randid";
$sql[] = "select rand, quest_id from temp2 where quest_id=$n";
$sql[] = "select t.id,t.rand, t.name,t.lname, t.email,t.phone, r.quest_id from temp1 t left join randid r on t.rand= r.rand";
foreach ($sql as $sql_command)
{
if ($debugging == 0)
{
$this->db->query($sql_command);
}
elseif ($debugging == 1)
{
echo $sql_command;
}
}
return $query->result();
}
Above code is in model and below code is in Controller
public function assign(){
$this->load->model("user_model");
$course=$this->input->post('course');
$n=$this->input->post('id');
$data['sel'] = $this->user_model->seememberfilter($course,$n);
$this->load->view('assign',$data);
}
mysql query are executing well in phpmyadmin. I checked it
What I want: I want to execute mysql query in CI successfully .
I am editing this and giving you sql table complete details
DROP TABLE IF EXISTS `member`;
CREATE TABLE IF NOT EXISTS `member` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rand` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`course` text NOT NULL,
`gender` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`state` varchar(255) NOT NULL,
`zip` varchar(255) NOT NULL,
`comment` text NOT NULL,
`Aboutme` text NOT NULL,
`dat` varchar(255) NOT NULL,
`tim` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `member` (`id`, `rand`, `email`, `name`, `lname`, `phone`, `dob`, `course`, `gender`, `address`, `city`, `state`, `zip`, `comment`, `Aboutme`, `dat`, `tim`) VALUES
(1, 'jrf20180961828', 'kk122344545#hotmail.com', 'Kishan', 'Yadav', '9717111111', '2018-09-01', 'paper first,Political Science,Philosophy,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'Good person.', '', '06-09-2018', '11:24:16pm'),
(2, 'jrf20180914721', 'kk1#gmail.com', 'Rohan', 'Yadav', '9717111111', '2018-09-01', 'paper first,Philosophy,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'Good Person.', '', '06-09-2018', '11:25:44pm'),
(5, 'jrf20180958284', 'ykishan94612121#gmail.com', 'kiran', 'Singh', '9717111111', '2018-07-07', 'paper first,Political Science,History,', 'female', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'nnbmnm', '', '10-09-2018', '10:11:34pm'),
(4, 'jrf20180932851', 'kk12#gmail.com', 'Pankaj', 'Yadav', '9717111111', '2018-09-01', 'paper first,Philosophy,Psychology,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'nmbmbn', '', '10-09-2018', '10:10:19pm'),
(6, 'jrf20180929250', 'hjh#gmail.com', 'John', 'Corter', '9717111111', '2018-09-06', 'paper first,History,', 'male', 'Diamond Auto Mobiles', 'Belthara road', 'ballia', '221715', 'sxs', '', '11-09-2018', '12:09:49am');
COMMIT;
And second table is
DROP TABLE IF EXISTS `assignment`;
CREATE TABLE IF NOT EXISTS `assignment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`rand` varchar(255) NOT NULL,
`course` varchar(255) NOT NULL,
`quest_id` varchar(255) NOT NULL,
`time` varchar(255) NOT NULL,
`date` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `assignment` (`id`, `rand`, `course`, `quest_id`, `time`, `date`) VALUES
(1, 'jrf20180914721', 'paper first', '2', '10:05:48pm', '2018-09-10'),
(2, 'jrf20180961828', 'paper first', '2', '10:06:49pm', '10-09-2018'),
(3, 'jrf20180914721', 'History', '2', '10:08:03pm', '10-09-2018'),
(4, 'jrf20180958284', 'History', '2', '10:12:05pm', '10-09-2018'),
(5, 'jrf20180914721', 'paper first', '1', '10:19:23pm', '10-09-2018'),
(6, 'jrf20180932851', 'History', '3', '12:07:48am', '11-09-2018');
COMMIT;
And my output should be kind of this, I join two table to get this output.
Attached pic of my output
I get this output using above query. Sorry for my english.
After chat in db-fiddle:
select distinct t.id, t.rand, name, lname, email, phone, if(quest_id='2','2',NULL) as quest-id
from `member` t
left join assignment a on t.rand= a.rand
where t.course like '%History%'
and (a.course like '%History%') or a.id is null
Member constrained to course, assignment same course, quest(ion)_id 2 displayed if it was found, otherwise leave the field as NULL.
You can use transaction to separate Query execution
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();

Searching String In All Tables And Displaying It With Pagination Technique

My database has five tables:
Computer|Mobile|Tablet|MusicSystem|Camera
All the tables are in same structure like:
productID|ProductBrand|Price|userId
Here, I want to search product's brand name in all the field of productBrand in all the tables, where userId=$userId and limit is 10 then display it with pagination technique.
How can I create such a query in MySQLi and display it in PHP?
Thanks in advance.
try this...
select * from Computer c,Mobile m,Tablet t,MusicSystem ms,Camera cam where userId = $userId and (c.productBrand = searchingProductBrand or m.productBrand = searchingProductBrand or t.productBrand = searchingProductBrand or ms.productBrand = searchingProductBrand or cam.productBrand = searchingProductBrand ) limit 10
If you are following same structure for each category table,better structure is to categorize all into single table as follows
CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`category_name` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `category` (`id`, `category_name`) VALUES
(1, 'Computer'),
(2, 'Mobile'),
(3, 'Tablet'),
(4, 'MusicSystem'),
(5, 'Camera');
CREATE TABLE IF NOT EXISTS `products` (
`ProductId` int(11) NOT NULL AUTO_INCREMENT,
`ProductBrand` varchar(255) NOT NULL,
`Price` varchar(100) NOT NULL,
`UserId` int(11) unsigned NOT NULL,
`CatId` int(11) unsigned NOT NULL,
PRIMARY KEY (`ProductId`),
KEY `CatId` (`CatId`),
CONSTRAINT `products_ibfk_1` FOREIGN KEY (`CatId`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `products` (`ProductId`, `ProductBrand`, `Price`, `UserId`, `CatId`) VALUES
(1, 'Lenovo', '35000', 5, 3),
(2, 'Asus', '28350', 5, 2),
(3, 'Dell', '25000', 5, 3),
(4, 'MotoG', '12500', 5, 2),
(5, 'Samsung', '52000', 4, 1);
You can get your result using
SELECT * FROM products WHERE userId = '5'
Check the FIDDLE

php/mysql how to join three tables

I'm writing code for a school transcript system. However, I'm stuck in joining the tables which are the courses table I named 'causes', courses registered table I named 'courses_registered' and the students table 'students' actually the join works, but the problem is that data are repeated in multiples depending on how many data rows that are on the courses_registered table for example, if have 2 courses registered, I get 4 rows echoed out from all tables instead of two. so my question is, how can i join these three tables perfectly without data being repeated, when i loop through the data. this is the table structure for the three tables.
--
-- Table structure for table `courses`
--
CREATE TABLE IF NOT EXISTS `courses` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`course_code` varchar(255) NOT NULL,
`course_title` varchar(255) NOT NULL,
`cl` int(255) NOT NULL,
`level` int(255) NOT NULL,
`session` varchar(255) NOT NULL,
`semester` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `courses`
--
INSERT INTO `courses` (`id`, `course_code`, `course_title`, `cl`, `level`, `session`, `semester`) VALUES
(1, 'GSS 111', 'Use of English', 3, 1, '2009/2010', '1'),
(2, 'GSS 112', 'Nigerian History', 2, 1, '2009/2010', '1');
--
-- Table structure for table `courses_registered`
--
CREATE TABLE IF NOT EXISTS `courses_registered` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`course_id` int(255) NOT NULL,
`student_id` int(255) NOT NULL,
`score` int(255) NOT NULL,
`grade` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `courses_registered`
--
INSERT INTO `courses_registered` (`id`, `course_id`, `student_id`, `score`, `grade`) VALUES
(1, 1, 2, 60, 'B'),
(2, 2, 2, 80, 'A');
-- --------------------------------------------------------
--
-- Table structure for table `students`
--
CREATE TABLE IF NOT EXISTS `students` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`regno` varchar(255) NOT NULL,
`college` varchar(255) NOT NULL,
`dept` varchar(255) NOT NULL,
`level` varchar(255) NOT NULL,
`fname` varchar(255) NOT NULL,
`lname` varchar(255) NOT NULL,
`no_of_semesters` int(255) NOT NULL,
`gender` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`age` int(255) NOT NULL,
`mstatus` varchar(255) NOT NULL,
`nationality` varchar(255) NOT NULL,
`religion` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`phone` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `students`
--
INSERT INTO `students` (`id`, `regno`, `college`, `dept`, `level`,
`fname`, `lname`, `no_of_semesters`, `gender`, `dob`, `age`,
`mstatus`, `nationality`, `religion`, `address`, `email`, `phone`)
VALUES
(2, 'MOUAU 09/14508', 'CEET', 'Electrical Electronics Engineering',
'1', 'Nnamdi', 'Okoro', 2, 'Male', '24-07-1989', 25, 'Single',
'Nigerian', 'christian', 'Okpu Umiobo road, Aba',
'nokoro#gmail.com', '09056733333');
Then this is the query
<?php
$sql = "
SELECT c.id as course_id
, c.course_code
, c.course_title
, c.cl
, c.level
, c.session
, c.semester
, r.id as rid
, r.course_id
, r.student_id
, r.score
, r.grade
, s.id
, s.regno
, s.fname
, s.lname
, s.no_of_semesters
FROM courses_registered r
JOIN courses c
ON r.course_id = course_id
JOIN students s
ON s.id = r.student_id
WHERE s.id = '$id'
";
$result = mysqli_query($con,$sql) or die ('Could not show students records.'. mysqli_error($con) );
if (mysqli_num_rows($result) > 0 ){
//echo mysqli_num_rows($result);
while($row = mysqli_fetch_array($result) ){
$score[] = $row['score'];
$course_code[] = $row['course_code'];
$course_title[] = $row['course_title'];
$cl[] = $row['cl'];
$grade[] = $row['grade'];
}
Try change this
ON r.course_id = course_id
to
ON r.course_id = c.id

get the count of field and group concat

table structure is as follows
-- Table structure for table category
CREATE TABLE `category` (
`cat_id` int(10) NOT NULL auto_increment,
`heading` varchar(255) NOT NULL,
PRIMARY KEY (`cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `category` (`cat_id`, `heading`) VALUES
(1, 'Fashion'),
(2, 'Kids');
-- --------------------------------------------------------
-- Table structure for table `shop`
CREATE TABLE `shop` (
`store_id` int(10) NOT NULL auto_increment,
`shop_name` varchar(255) NOT NULL,
`cat_id` int(10) NOT NULL,
`subcat_id` int(10) NOT NULL,
PRIMARY KEY (`store_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `shop` (`store_id`, `shop_name`, `cat_id`, `subcat_id`) VALUES
(1, 'Test Store', 1, 1),
(2, 'Test Store 1', 1, 1),
(3, 'Another Store', 1, 3);
-- --------------------------------------------------------
-- Table structure for table `subcategory`
CREATE TABLE `subcategory` (
`subcat_id` int(10) NOT NULL auto_increment,
`cat_id` int(10) NOT NULL,
`heading` varchar(255) NOT NULL,
PRIMARY KEY (`subcat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `subcategory` (`subcat_id`, `cat_id`, `heading`) VALUES
(1, 1, 'Women'),
(2, 1, 'General'),
(3, 1, 'Men'),
(4, 2, 'Children');
if i use the below query i get the following output
SELECT
`category`.`heading` AS `category`
, `subcategory`.`heading` AS `subcategory`
, COUNT(`shop`.`subcat_id`) AS cnt
FROM
`test`.`shop`
INNER JOIN `test`.`subcategory`
ON (`shop`.`subcat_id` = `subcategory`.`subcat_id`)
INNER JOIN `test`.`category`
ON (`shop`.`cat_id` = `category`.`cat_id`)
GROUP BY `shop`.`subcat_id`
HAVING (COUNT(`shop`.`subcat_id`) !='');
categorysubcategorycnt
FashionWomen2
FashionMen1
but i want to group concat the subcategory like below
categorysubcategory
FashionWomen,2|Men,1
Try this
SELECT t.category,
GROUP_CONCAT(CONCAT(t.subcategory,',',t.cnt) SEPARATOR '|') `concat`
FROM (
SELECT
`category`.`heading` AS `category`
, `subcategory`.`heading` AS `subcategory`
, COUNT(`shop`.`subcat_id`) AS cnt
FROM
`shop`
INNER JOIN `subcategory`
ON (`shop`.`subcat_id` = `subcategory`.`subcat_id`)
INNER JOIN `category`
ON (`shop`.`cat_id` = `category`.`cat_id`)
GROUP BY `shop`.`subcat_id`
) t
GROUP BY t.category
Note group concat has a default limit of 1024 character but it can be increased by following the manual
Fiddle Demo
Not a recommended output format, but easily done with a nested subquery:
SELECT category,
group_concat(subcategory, ',', cnt separator '|') as vals
FROM (SELECT c.`heading` AS `category`, sc.`heading` AS `subcategory`,
COUNT(`shop`.`subcat_id`) AS cnt
FROM `test`.`shop` s INNER JOIN
`test`.`subcategory` sc
ON s.`subcat_id` = sc.`subcat_id`) INNER JOIN
`test`.`category` c
ON s.`cat_id` = c.`cat_id`
GROUP BY c.`heading`, sc.`heading`
) sc
GROUP BY category;
Your having clause is unnecessary. It is just checking that there is at least one row for each group. But there is one, because you are using inner join.

Advanced many2many query for MYSQL

I im trying to build a imagegallery where people have access to different groups and the groups decide what catalogues and images they are allowed to see.
I though many2many structure would be best for this.
So far, ive manage to build the database like this:
image (image_name, image_file, image_id)
catalog (catalog_id, catalog_name)
supplier (supplier_id, supplier_name)
user (name, user_id)
image2cataloge (image_id, catalog_id)
image2supplier (image_id, supplier_id)
catalog2supplier (catalog_id, supplier_id)
user2supplier (user_id, supplier_id)
So... that been said, saving images and making supplier (or group if you want), adding users to supplier and linking images to supplier and catalogues is no problem. Inserting is no problem.
But selecting the right images based upon the users supplier setting and catalog they are in is harder.
For example, I have a user with user_id 1, which have access to supplier_id 1. supplier_id 1 have access to view catalogue 1, which holds images with image_id 1 and 2.
But supplier_id 1 only have access to image_id 2.
All this settings are stored in the database. How do I do the select query?
This is what i've tested;
//$catalog_id is the catalog_id we are in
//$user_id is the current users user_id
$sql = "SELECT i.*
FROM image i, user u, catalog cat, supplier s, supplier2user s2u, supplier2catalog s2c, image2catalog i2c, image2supplier i2s
WHERE u.id = '".$user_id."'
AND s2u.user_id = '".$user_id."'
AND s2u.supplier_id = s.id
AND s2c.catalog_id = '".$catalog_id."'
AND i2c.catalog_id = '".$catalog_id."'
AND i2s.supplier_id = s.id
AND s2c.supplier_id = s.id
GROUP BY i.id
ORDER BY i.name ASC
But when ive added more than one image, all images are shown for all users in all catalogues.
EDIT (2010/02/05):
Okey, so I've figured out how to at least show correct images in correct catalog. I do this by doing following:
$sql = "SELECT i.*
FROM
image i
INNER JOIN image2catalog i2c
ON i.id = i2c.image_id
AND i2c.catalog_id = '".$pages_level_0[$i]['id']."'
GROUP BY i.id
;";
This let's me output the correct images that belongs in the catalog the user is visiting at the moment. Now I just need to edit this query to filter out all images the user doesn't have access to. I very grateful for any help you can provide!
EDIT 2010/02/09:
---
CREATION SCHEME
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`email` varchar(250) NOT NULL,
`password` varchar(50) NOT NULL
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `imagebank` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(250) character set utf8 NOT NULL default '',
`url` varchar(250) character set utf8 NOT NULL default '',
`childof` varchar(250) character set utf8 NOT NULL default '',
`hide` tinyint(4) NOT NULL,
`publishdate` varchar(14) NOT NULL,
`expiredate` varchar(14) NOT NULL,
`editdate` varchar(14) NOT NULL,
`editbygroup` varchar(250) NOT NULL,
`openby` varchar(250) NOT NULL,
`opendate` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci;
CREATE TABLE `imagebank_image` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(250) NOT NULL,
`img` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `imagebank_image2catalog` (
`image_id` int(11) NOT NULL,
`catalog_id` int(11) NOT NULL,
PRIMARY KEY (`image_id`,`catalog_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `imagebank_image2supplier` (
`image_id` int(11) NOT NULL,
`supplier_id` int(11) NOT NULL,
PRIMARY KEY (`image_id`,`supplier_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `imagebank_supplier` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `imagebank_supplier2catalog` (
`supplier_id` int(11) NOT NULL,
`catalog_id` int(11) NOT NULL,
PRIMARY KEY (`supplier_id`,`catalog_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE `imagebank_supplier2user` (
`supplier_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`supplier_id`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SOME DATA:
INSERT INTO `imagebank` (`id`, `name`, `url`, `childof`, `hide`, `publishdate`, `expiredate`, `editdate`, `editbygroup`, `openby`, `opendate`) VALUES
(1, 'Test 1', 'test-1', '', 0, '20100204230233', '', '', '', '', ''),
(2, 'Test 2', 'test-2', '', 0, '20100204230244', '', '', '', '', '');
INSERT INTO `imagebank_image` (`id`, `name`, `img`) VALUES
(1, 'Test img 1', 'labb_9noq80bik5.jpeg'),
(2, 'Test img 2', 'labb_53626114dz.jpeg');
INSERT INTO `imagebank_image2catalog` (`image_id`, `catalog_id`) VALUES
(1, 1),
(2, 2);
INSERT INTO `imagebank_image2supplier` (`image_id`, `supplier_id`) VALUES
(1, 2),
(2, 1);
INSERT INTO `imagebank_supplier` (`id`, `name`) VALUES
(1, 'Supplier1'),
(2, 'Supplier2'),
(3, 'Supplier3');
INSERT INTO `imagebank_supplier2catalog` (`supplier_id`, `catalog_id`) VALUES
(1, 2),
(2, 1);
INSERT INTO `imagebank_supplier2user` (`supplier_id`, `user_id`) VALUES
(1, 1),
(1, 11),
(1, 12),
(2, 1),
(2, 10),
(3, 1);
INSERT INTO `user` (`id`, `email`, `password`) VALUES
(1, 'User1#test.com', 'ff02dd5s33taa2ba5ff7c2c4d3327e444'),
(10, 'User2#test.com', 'ff02dd5s33taa2ba5ff7c2c4d3327e444'),
(11, 'User3#test.com', 'ff02dd5s33taa2ba5ff7c2c4d3327e444'),
(12, 'User4#test.com', 'ff02dd5s33taa2ba5ff7c2c4d3327e444');
WOW, now thats alot of stuff :P So I know that the tables, specially for "catalogs" which i call just "imagebank" might look abit strange. But I do have my reasons and thats not really the issue :) Its part of an even bigger picture. Hope this helps you to help me. Thanks again.
It looks like if you are passing in the user and catalogue id's then the supplier doesn't matter.
If you required the supplier information in the result, that would be a different matter.
It feels like you shouldn't be involving the user in this query at all as you seem to be looking for the images in a catalogue that are owned by a particular supplier.
If that is the case, then I would drop the requirement for the user id in the query and use the supplier id instead.
I am assuming that the user would have done the following to get to the point where they would be initiating this query:
login - obviously :)
click on 'list suppliers'
click on a supplier
click on a catalog
Either way you are going to have to do a lot of INNER JOIN's. For instance the query to retrieve the list of suppliers for a given user would be something like
SELECT
s.supplier_id,
s.Supplier_name
FROM
supplier s
INNER JOIN
user u
INNER JOIN
user2supplier u2s
ON
u.user_id = u2s.user_id
ON
u2s.supplier_id = s.supplier_id
WHERE
u.user_id = 3 -- for example...
(now, I haven't tested the SQL, but I think that is right...)
Let me know if I'm on the right track - if I have helped, I'd be happy to help some more if I can

Categories