php - Count the number of rows in MySQL table with criteria depending on other table -
i've got 2 tables:
content: id access 1 3 2 5 3 9 viewlevels: id group 1 [10,12,15] 2 [8,12,11] 3 [9,10,5]
the access field in content related id field in viewlevels.
i select rows in viewlevels depending on current user group. example, if group = 10, query select rows 1 , 3. if group 12, select rows 1 , 2, etc. i'm using following query:
$query="select id #__viewlevels rules '%$group%'";
my challenge count number of rows column id in table content access matches selected id's above query on table viewlevels.
i tried following code returning error: undefined variable: nartigos
$query="select count(id) #__content access in (select id #__viewlevels rules '%$group%')"; if ($stmt = mysqli_prepare($link, $query)) { /* execute query */ mysqli_stmt_execute($stmt); /* store result */ mysqli_stmt_store_result($stmt); $nartigos=mysqli_stmt_num_rows($stmt); /* close statement */ mysqli_stmt_close($stmt); }; echo "nÂș de artigos " .$nartigos;
first of all, should normalize data. consider having many-to-many join table viewlevels instead of having groups in 1 row. might this:
access_id group_id 1 10 1 12 1 15 2 8 2 11 2 12 3 5 3 9 3 10
that make query simple as
select c.id `content_id`, count(v.access_id) `content_count` content c inner join viewlevels v on c.access_id = v.access_id v.group_id = ? group c.id
here ?
group id querying against.
without normalization (which again recommend do), still use join, this:
select c.id `content_id`, count(v.access_id) `content_count` content c inner join viewlevels v on c.access_id = v.access_id v.group '%?%' group c.id
Comments
Post a Comment