I'm having trouble getting some data.... I was wondering if someone can help me,
I have 4 tables (likes, follow, comment, users)
I want to be able to populate my page when a user likes/comments/follows/etc... (if a user is following a particular user).
likes
idlikes idusers iditem
1 1 5
2 2 4
3 2 22
follow
idfollow idusers_follower idusers idbusiness
1 1 2
2 1 3
3 1 4
4 4 2
5 4 1
comment
idcomments idusers text
1 1 asfd
2 2 safd
users
idusers
1
2
3
4
For example if I am id user #1, I'm following users #2, #3, #4
My page would populate to show:
#2 likes item #4, #22.
#4 is following #2 (because I'm following #4, this is why its showing)
#2 comments "safd"
I'm not sure what is the best way to display this? I currently have multiple functions querying on table at a time, and I'm working on merging the arrays together? Or should I use join tables? Which I'm trying now...
Get users that I'm following.
$feeds = new feed();
$meID = 1;
$query = "SELECT idusers FROM follow WHERE iduserse_follower = ?";
$users = $dbh -> prepare($query);
$users -> execute(array($meID));
while($following = $users -> fetch(PDO::FETCH_ASSOC)){
$follow = $following['idusers']; //This will get all of useres I'm following
$populate = $feeds->feed_all($follow); // from function
}
Query
class feed()
{
public function feed_all($idusers)
{
// SYNTAX HELP //////////////////////
$query = "SELECT
f.idusers_follower,
f.idusers,
l.iditem,
c.text
FROM follow f, users u
JOIN likes l
ON l.idusers = f.idusers
JOIN comment c
ON c.idusers = f.idusers
WHERE f.idusers_follower = ? AND f.idusers_follower = l.idusers AND f.idusers_follower = c.idusers AND f.idusers = u.idusers"
$pop = $dbh->prepare($query);
$pop ->execute($idusers);
// while loop to return value
while($row = $pop -> fetch(PDO::FETCH_ASSOC))
{
$feed_data[]=$row;
}
return $feed_data;
}
}
This is where I'm stuck. :( I'm not even sure if I'm doing the statement right?
++++++++++ EDIT: ++++++++++++
I have edited to add idbusiness
Now since I'm following #4, it would also show up that #4 is following #1.
Your current approach of performing three separate queries is as good as any; you can combine them into a single resultset using UNION, which would be useful if you wanted to sort the combined results by some field (e.g. activity timestamp) and/or limit the combined results:
SELECT idusers, 'likes' AS what, likes.iditem AS detail
FROM likes JOIN follow USING (idusers)
WHERE follow.idusers_follower = 1
UNION ALL
SELECT f1.idusers, 'follows', f2.idusers
FROM follow f1 JOIN follow f2 ON f1.idusers = f2.idusers_follower
WHERE f1.idusers_follower = 1
UNION ALL
SELECT idusers, 'commented', comment.text
FROM comment JOIN follow USING (idusers)
WHERE follow.idusers_follower = 1
See it on sqlfiddle.
Related
I've 4 table for a newsletter. Newsletters, Subscribers, Subscriber Groups and Selected Subscriber Groups. I've choose subscriber groups in campaign edit area, and its save selected groups to tbl_newsletter_groups table like;
tbl_newsletters
NID title details
1 text 1 content 1
2 text 2 content 2
tbl_subscriber_groups
GID group_name
5 group 1
6 group 2
tbl_subscribers
SID GID email name
10 5 sub1#mail.com sub1 name
11 6 sub1#mail.com sub1 name
tbl_newsletter_groups
NGID NID GID
15 1 6
16 1 6
17 1 6
I want to show total selected subscriber count when I list newsletters in my page. My soulution works fine, Im looking for simple and clearly statement, there any faster way available like in single newsletter list statement?
Here my own count style (yes I know its too bad and long way);
$subGID = array();
$list = $myconn->query("SELECT * FROM tbl_newsletters");
while($listRs = $list->fetch_assoc()){
$grps = $myconn->query("SELECT * FROM tbl_newsletter_groups WHERE NID=". $listRs['NID'] ."");
while($grpsRs = $grps->fetch_asscoc()){
$subGID[] = $grpsRs['GID'];
} $grps->free();
$subs = implode(" OR GID=",$subGID);
$count = mysqli_num_rows($myconn->query("SELECT ID FROM tbl_subscribers WHERE GID=". $subs));
echo('Total Selected Subscriber: '.$count);
} $list->free();
Thanks.
The search term you want is "set-based logic".
Your thinking is sound: you need everything from tbl_newsletters, then you need to count results from tbl_subscribers, but in order to get those you need information from tbl_newsletter_groups.
In SQL, that's an indication you want a join. You've already discovered the conditions you need, you just don't know the syntax. A reference manual can help there.
Now you'll have a bunch of records, which you need to smash into a smaller number of records. You need aggregation functions and a GROUP BY clause.
So here's the final query:
SELECT n.NID, n.title, n.details, COUNT(s.SID)
FROM tbl_newsletters AS n
JOIN tbl_newsletter_groups AS g ON n.NID = g.NID
JOIN tbl_subscribers AS s ON g.GID = s.GID
GROUP BY n.NID
I got the two tables(Table1 and Table2):
Table1:
id hits url
1 11 a
2 5 b
3 6 c
4 99 d
5 14 e
Table2:
id url 2014.04.13 2014.04.14
1 a 0 5
2 b 0 1
3 c 0 3
4 d 0 60
5 e 0 10
hi all,
Table1 one contains the actual hits(which are always up-to-date) and Table2 to statistics(which are done every day at midnight). The columns id(unique number) and url are in both tables the same. So they got the same amount of rows.
So i create every day a new column(with the date of today) and copy the column hits from the table 'Table1' into the new created column into the table 'Table2'
First i alter Table2:
$st = $pdo->prepare("ALTER TABLE Table2 ADD `$today_date` INT(4) NOT NULL");
$st->execute();
Then i cache all entries i need from Table1:
$c = 0;
$id = array();
$hits = array();
$sql = "SELECT id, hits FROM Table1 ORDER BY id ASC";
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id[$c] = $row['id'];
$hits[$c] = $row['hits'];
$c++;
}
At last i update Table2:
for ($d = 0 ; $d < $c ; $d++)
{
$id_insert = $id[$d];
$sql = "UPDATE DOWNLOADS_TEST SET `$datum_det_dwnloads`=? WHERE id=?";
$q = $pdo->prepare($sql);
$q->execute(array($hits[$d], $id[$d]));
if($q->rowCount() == 1 or $hits[$d] == 0) // success
$hits[$d] = 0;
else // error inserting (e.g. index not found)
$d_error = 1; // error :( //
}
So what i need is to copy(insert) a column from one table to another.
The two tables are having ~2000 elements and the copying as described above takes around 40 sec. The bottleneck is the last part (inserting into the Table2) as i found out.
One thing i found is to do multiple updates in one query. Is there anything i can do besides that?
I hope you realise that at some point your table will have irrational number of columns and will be highly inefficent. I strongly advise you to use other solution, for example another table that holds data for each row for each day.
Let's say you have a table with 2000 rows and two columns: ID and URL. Now you want to know the count of hits for each URL so you add column HITS. But then you realise you will need to know the count of hits for each URL for every date, so your best bet is to split the tables. At this moment you have one table:
Table A (A_ID, URL, HITS)
Now remove HITS from Table A and create Table B with ID and HITS attributes). Now you have:
Table A (A_ID, URL)
Table B (B_ID, HITS)
Next move is to connect those two tables:
Table A (A_ID, URL)
Table B (B_ID, A_ID, HITS)
Where A_ID is foreign key to attribute "A_ID" of Table A. In the end it's the same as first step. But now it's easy to add date attribute to Table B:
Table A (A_ID, URL)
Table B (B_ID, A_ID, HITS, DATE)
And you have your solution for database structure. You will have a lot of entries in table B, but it's still better than a lot of columns. Example of how it would look like:
Table A | A_ID | URL
0 index
1 contact
Table B | B_ID | A_ID | HITS | DATE
0 0 23 12.04.2013
1 1 12 12.04.2013
2 0 219 13.04.2013
3 1 99 13.04.2013
You can also make unique index of A_ID and DATE in Table B, but I prefer to work on IDs even on linking tables.
I've got two 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 is related with the id field in viewlevels.
I select the rows in viewlevels depending on the current user group. So for example, if group is = 10, my query will select rows 1 and 3. If the group is 12, it will select rows 1 and 2, etc. I'm using the following query:
$query="SELECT id FROM #__viewlevels WHERE rules LIKE '%$group%'";
My challenge is to count the number of rows for column id in table content where the access matches with the selected id's from the above query on table viewlevels.
I tried the following code but it is returning the error: undefined variable: nartigos
$query="SELECT count(id) FROM #__content WHERE access IN (SELECT id FROM #__viewlevels WHERE rules LIKE '%$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, you really should normalize your data. Consider having a many-to-many join table for viewLevels instead of having all groups in one row. That might look like this:
access_id group_id
1 10
1 12
1 15
2 8
2 11
2 12
3 5
3 9
3 10
That would make your query as simple as
SELECT c.id AS `content_id`, COUNT(v.access_id) AS `content_count`
FROM content AS c INNER JOIN viewLevels AS v
ON c.access_id = v.access_id
WHERE v.group_id = ?
GROUP BY c.id
Here ? is the group id you are querying against.
Without normalization (which again I STRONGLY recommend you do), you would still use a join, but it would look like this:
SELECT c.id AS `content_id`, COUNT(v.access_id) AS `content_count`
FROM content AS c INNER JOIN viewLevels AS v
ON c.access_id = v.access_id
WHERE v.group LIKE '%?%'
GROUP BY c.id
you need to "join" your tables.
the sql command cant query two tables seperately.
when you "join" 2 tables in your sql, think of it as making one virtual/temporary table in the air, of the 2 tables which you can then query.
this is quite a good intro http://www.sitepoint.com/understanding-sql-joins-mysql-database/
I have a table that looks like this
id | itemID | catID | Title
----------------------------------------------------------------------------
0 3 4 Hello
1 3 6 Hello
2 4 4 Yo
3 4 8 Yo
4 5 2 Hi
5 1 3 What
I want to do a MySQL PHP Select that only gets one occurrence of the itemID. As you can see they are the same item, just in different categories.
This is what I tried
SELECT * FROM Table GROUP BY itemID
That didn't seem to work, it still just shows duplicates.
Is this what you are looking for? http://www.sqlfiddle.com/#!2/5ba87/1
select itemID, Title from test group by itemID;
As far as MySQL is concerned, the data is all unique, since you want all of the columns. You have to be more specific.
Do you just want the itemID (or other column)? Then say so:
select [column] from Table GROUP BY itemID
Do you want the last entry of a particular item ID? Then say that:
select * from Table where itemID = 1 ORDER BY id DESC
Or the first one?
select * from Table where itemID = 1 ORDER BY id
If none of these are what you want, then you probably need to restructure your tables. It looks like you want different categories for your items. If so, then you'll want to split them out into a new join table, because you have a many-to-many relationship between Items and Categories. I recommend reading up on database normalization, so you're not duplicating data (such as you are with the titles).
If you want everything for the distinct itemIDs, you could certainly take a long route by doing one selection of all of the distinct itemIDs, then doing a series of selections based on the first query's results.
select distinct(`itemID`) from Table
Then in your PHP code, do something like this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$itemID = $row['itemID'];
$sql2 ="SELECT * FROM Table WHERE 1 and `itemID`=\"$itemID\" limit 1";
$result2 = #mysql_query($sql2, $connection);
while ($row2 = mysql_fetch_array($result2))
{
$id = $row2['id'];
$itemID = $row2['itemID'];
$catID = $row2['catID'];
$Title = $row2['Title'];
}
}
Hi simple question i guess, but cant figure out how to list the mysql sql the way i want it.
Basiclly in one row I have CityID's I want to be able to pull out the CityID's that == 14 and show them at the top of the return (BUT NOT AS A COUNT)
for e.g
Perth == 15
Melbourne == 14
Preston == 14
Sydney == 13
currently they show like this
Sydney == 13
Perth == 15
Melbourne == 14
Preston == 14
my code
$sth = mysql_query("SELECT users.id as id, users.username as username, profile.defaultpictureid as picture FROM users, userprofiles as profile WHERE online = '1' AND profile.country = ".$this->country." AND profile.state = ".$this->state." AND profile.city = ".$this->city." ORDER BY if (profile.city = 12276,0,1)");
The code above seems to be working now.
However also seems to print out the data twice.
[{"id":"7","username":"A","picture":"0"},{"id":"1","username":"B","picture":"0"},{"id":"1","username":"B","picture":"1"},{"id":"7","username":"A","picture":"1"}]
You're selecting from two tables (users and profiles), but have no specified any kind of relationship between when in your where clause, so what you're getting is the Cartesian product of the two, which is why you're getting the duplicated results.
I'm guessing your query should look something more like this:
SELECT users.id as id, users.username as username, profile.defaultpictureid as picture
FROM users, userprofiles as profile
WHERE
online = 1 AND
profile.country = {$this->country} AND
profile.state = {$this->state} AND
profile.city = {$this->city} AND
users.id = userprofiles.userid <---the join condition for the two tables
ORDER BY if (CityID = 14, 1, 0), profile.city
You can apply an if clause in the sorting
order by if(CityID = 14,0,1)