fetching multiple usernames from a database - php

I have a comments section on a website i'd like to streamline a bit if possible so it's not as much of an impact on the database. When a user selects a post, and if it has comments associated with it, it lists the comments. when the comments list, it fetches the username from another table. I store the id for the user in the comments table, and use that id to select the record from the users table. and displays as "user" said:
lets say i have 1000 comments on a post, it will hit the users table 1000 times to grab user names. I think this is probably a bad design. i thought of a few solutions, but don't know what would be recommended in this situation.
should i just be storing the username inside the comments table?
should i store all of the usernames already called in a session array?
put all of the usernames in a file, and call from the file?
or is there another solution that i haven't thought of?
i'm kind of confused. I thought i was doing the right thing by using the IDs in the comment table, and then using it to fetch the username, but after reading about a million posts on using less impact on the database, i'm starting to question myself.
WOW, thanks for all of the useful answers. here is the table scheme, i don't know why i didn't put in in originally.
comments table for jokes:
id | author_id | joke_id | date_created | body
---+-----------+---------+--------------+-----
1 | 3 | 2 | 2011-06-12 | this is a comment
and for the users:
id | user_name | password | email | date_joined | visible
---+-----------+----------+-------+-------------+---------
3 | booboo | password | email | todays_date | 1

This is what JOINs are for - so that you can run a single query and efficiently get the combined information from multiple tables. E.g.:
SELECT comments.id, comments.content, users.name
FROM comments
JOIN users ON comments.user = users.id
WHERE comments.id in (1,2,3)
would look up the 3 comments with id 1, 2, and 3, plus also get the username of each commenter, and return rows that looked like this:
comments.id | comments.content | users.name
------------+-------------------+---------
1 | "First comment." | "Poster1"
2 | "Second comment." | "Poster2"
3 | "Third comment." | "Poster3"

It sounds like you have a userID field in your comments table, but need to look up the username, correct? If so, a JOIN would be the best solution.
Something like:
SELECT *
FROM `comments`
LEFT JOIN `users` ON `users`.`id` = `comments`.`userid`
WHERE `postid`='1'
To read more on joins and their endless possibilities, read up here

SELECT * FROM comments LEFT JOIN users ON comments.posterid = users.id
Google for LEFT JOIN for more info :)

Do you allow the same username to be used more than once? If not, then I would use the username field as the PK of your users table and store that in the commentstable as the FK. That'll solve your issue nicely.
If changing the PK of your users table is too much of an issue, then just store the username in the comments section since you can still use that select a single record from your users table.

Related

Like structure table with Laravel and showing the most popular content at top

I am using Laravel to creating a website, my users can post questions and other users can write their comments under the post, each comment have Up vote and Down vote, and users can voting for comments.
I need most liked (Up vote) shows topper than others..
This is my database structure and I join them together:
comment table:
comment_id | question_id | user_id | timestamp
up and down votes table (like):
like_id | comment_id | like_type | user_id | timestamp
note:like_type is an enum on mysql and its values are upvote and downvote.
1-What is the mysql query and Laravel codes for that?
2-Is my database Structure right?
1.Calculate SUM belongs to Each Comment
2.Make it order by Desc
select * from (
select ct.comment_id,ct.question_id,
ct.user_id,SUM(case when vt.like_type='upvote' then 1 else -1 end )
cnt from commenttable ct
from votestable
vt left join
on
vt.comment_id=ct.comment_id
)D order by D.cnt desc

Attempting to list data using ID from a particular table

I have one table which stores user info, including the username.
Another table contains a list of user id's and the user id's of those that they have favorited.
I am trying to figure out the query for listing the usernames of those that user id 1 has favorited.
In my query, assuming that I am uid 1, I need the usernames of uid 3 and 5, but instead
in sqlfiddle I am attempting to join them but I keep getting my username, cjaredrun, instead of the matched usernames for each favorite.
You can see what I have been trying here: http://www.sqlfiddle.com/#!2/c5836/1
Any guidance appreciated
You just need a simple join:
SELECT u.username FROM fav_user f
JOIN users u ON u.uid = f.matchuid
WHERE f.uid = 1
ORDER BY datetime
Fiddle here.
Output:
| USERNAME |
|----------|
| jolet |
| jane |

Select many relational ID in one shot(MYSQL)

so we have:
table users
id name password parent_id
the first user have the id 1, and others have the parent_id 1, so I select all the users that have the parent_id == 1 - they are the childs of the user with 1, okay its all right, but now i need to select the users that have the parent_id of the selected before users with they id, if they exists of course
user with id 1
/ | \
/ | \
/ | \
users with parent_id 1
user id 2 user id 3 id user 4
| | |
| | |
| | |
and here is the same, I need to select all the users that have the parent_id 2, 3, 4 for each of those user, its is something like a pyramide(triangle) from the top to the bottom
So the question is how can i make a query that will select it in one shot, not in many queries by extracting the id and then make other query - its not good i think
do you have an idea??
Here is a question, that covers your problem:
Is it possible to query a tree structure table in MySQL in a single query, to any depth?
Query below works only for finding children and grand-children of a single user and is a product of misunderstanding the question!
You could try joining user table on itself twice.
SELECT * FROM users as up
JOIN users as u on up.id=u.parent_id
JOIN users as uc on u.id=uc.parent_id
WHERE up.id={$grandParentUserId}
Aliases: up = user's parent, u = user, us = user's child.
Definitely not a pretty solution, but it's a single request.
I see you are using CI. You can have a look at this answer. Somewhat related to your question. You can select the users with NULL parent ID first and then populate their children
https://stackoverflow.com/a/9937130/876117

Determining Which Table the Result Came From

I currently have a couple tables that I'm joining together so I can form all of the relevenat results into a news feed of recent activity. The only problem I'm having is figuring out which table the information is coming from.
$recentActivity = mysql_query("
SELECT *
FROM members
LEFT JOIN market
ON members.id = market.user
LEFT JOIN sales
ON members.id = sales.uid
WHERE members.id='$id'
");
I'm then running a while loop
<? while ($recent = mysql_fetch_assoc($recentActivity)) { ?>
If the result in the loop comes from the market table I would like to be able to echo "market" or something like that and do the same if it comes from the sales table.
Hope this makes sense.
You cannot. The only possible way is to explicitly specify aliases for all (necessary) market table fields. Like:
SELECT members.*,
market.id AS market_id,
market.foobar AS market_foobar
etc. The same with sales table
There's this convention that a lot of people use. If I have a table, Users:
--------------------------------
| user_username | varchar(20) |
| user_email | varchar(40) |
| user_phone | varchar(13) |
---------------------------------
This allows you do have joins and know specifically what table that data came from. It's a sort of namespacing.
If you can rename your fields in the table, I would heavily consider it.

Nested or Joins query for MySQL using PHP

I have many a times tried using nested query for MySQL in PHP, but it does not work. Is it not possible to do nested/Joins queries?
Just a Scenario:
I have two tables one table with user id and the other with data. User logins and with sessions I have to cross check two different tables with user id (user and data). Is it not possible to nest/join these two tables to write a single query statement.
In short is nesting or joining two or more tables permitted in PHP coding?
YES, it is possible to join two or more tables in MySQL (and therefore, also when using PHP).
You need to post your table schema, if you want us to show a relevant join query. You could, however, try something like:
SELECT * FROM user AS t1
CROSS JOIN data AS t2
ON t1.userid=t2.userid
WHERE t1.userid='154'
(This query presumes that there always will be one row with the userid in both tables. You should use LEFT JOIN instead of CROSS JOIN to return a row even if there is no row in data for the userid. 154 is just an example userid.)
Have a look at http://dev.mysql.com/doc/refman/5.5/en/join.html for information on the JOIN syntax.
users
| user_id | username | password | enabled |
|---------|----------|----------|---------|
| 1 | john | sgsd2gg | 1 |
| 2 | jane | sdshdhd | 0 |
users_data
|udata_id| user_id | some_column |
|--------|---------|-------------------|
| 1 | 1 | Some title |
| 2 | 2 | another title |
Since you haven't posted your table schema, I can't give you an exact solution. But supposing you have a users table and a users_data table, where users_data are owned by a user. You can do a join on the table to retrieve all the data.
SELECT * -- Don't select all fields unless you need it
FROM users U LEFT JOIN users_data UD ON U.user_id = UD.user_id
WHERE U.user_id = 1
This would pull all the records for user with an ID of 1. This is a very simplistic join, but it should give you an idea.
Here's an example that visually describes the different options you can use : SQL Join Differences

Categories