Pulling data from multiple mysql tables - php

Hello I am creating an API for my android application and pulling posts from database so far I successfully pull the posts with its photo and caption yet I have no idea how to pull the posts user profile picture and username which are stored in my users table. Please anyone to point me in the right direction would be a saviour. This is the code I use in php to pull the post's details
$sql = "SELECT * FROM Posts";
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
}

What you want is a join. A good reference for the basics can be found on w3schools.
Basically (and without knowing the details of your database) there has to be a connecting ID in both tables, in this case a user id. For example:
SELECT
Posts.id,
Posts.user_id,
Posts.caption,
Posts.photo,
Users.user_id,
Users.username,
Users.profile_pic
FROM Posts
INNER JOIN Users ON (Users.user_id = Posts.user_id);
This will get every post and for each post it will fetch the relevant line(s) from the Users table (where the user_id is the same as in the post).

Related

PHP and MySQL, Using a foreign key to get data from another table where it originates from

This question involves 3 tables that I have in PHPmyAdmin called:
tblShoots
tblMemberOnShoot
tblMember
I need to run a query on a users dashboard which tells them, which photoshoots they have been to.The tblmemberOnShoot table is shown below, if I was to click on through an entry under fldShootID (which is a foreign key), it would take me to tblShoots which holds the shoot details, in there I need to pull out fldShootLocation.
At the moment my query is shown below which doesn't entirely give the output needed, I need help with the join?
<?php
$query = "SELECT * FROM `tblMembersOnShoot` WHERE `fldMemberID` = 1";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['fldShootID']."<br>";
}
?>
Output on the page:
As you said, a JOIN is the way to go. Here's what I'd suggest:
SELECT fldShootLocation FROM tblMember
LEFT JOIN tblMembersOnShoot
ON tblMembersOnShoot.fldMemberID = tblMember.fldMemberID
LEFT JOIN tblShoots
ON tblShoots.fldShootID = tblMembersOnShoot.fldShootID
WHERE tblMember.fldMemberID = 1

How to get top most liked post among my all post from mysql using PHP

As per the below code status='notlove' shows that the user already liked, and status='love' indicated that user liked it and again unlike this post,
The Qus is, the code gives me the proper result but when i liked a new post,
it is not showing me the proper result, instead of showing most liked post it is showing me the New Post result, How can i solve this Issue?
Kindly refer my Table View also
I'm getting the user which is logged in
$id = $_SESSION["id"];
//query for getting the top most timeline id of current log in user
$sql= "SELECT *
FROM lovetimeline
INNER JOIN (
SELECT userId, MAX(timelineId) AS Maxscore
FROM lovetimeline
GROUP BY userId
) topscore
ON lovetimeline.ownerId = '$id'
AND status='notlove'
AND lovetimeline.timelineId = topscore.maxscore";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
//getting the top liked post from table
$_SESSION["toppost"] = $row["timelineId"];
}

Appending php array for desired row outputs

I am building a friends list of logged in user verified by session id. I have code that query's, results, and loops perfectly. BUT, it is posting an integer (maybe the id#?), (as this is my unique identifying condition of the select query) AND what I want is to output the (users) table rows of "firstname" and "lastname" instead of the user-id!
Sounds simple enough, yet, I lack the knowledge to make it work! So, here I am inquiry from the world of coders for help! Any assistance would be greatly appreciated!
Here is my code:
// Get Friend Array
$sql = "SELECT * FROM users
INNER JOIN friends
ON users.id = friends.id
WHERE (friends.user1='$u' OR friends.user2='$u' AND friends.accepted='1')";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
array_push($my_friends, $row["user2"]);
array_push($my_friends, $row["user1"]);
}
//remove your id from array
$my_friends = array_diff($my_friends, array($u));
//reset the key values
$my_friends = array_values($my_friends);
mysqli_free_result($query);
// Loop through $my_friends array and build results
foreach($my_friends as $friends => $v2);
$friends .= ' ';
}
Here is my html code:
<ul data-role="listview" data-autodividers="true">
<?php
echo "<li>$friends</li>";
?>
</ul>
It is the last line of code
$friends .= ' ';that I'm trying to workout. How the syntax of that line should be to add ($row["users.firstname"] and $row["users.lastname"]) and somehow not list the user "$id #" that is joining the two tables of (users) and (friends) in the select query!
It may be that I need a different array altogether for what I want, and If you know of the right way to do this, please inform me of how to do it...Thank you all!
What I understood that you are missing User's id in row. This issue is because php array can not have two keys with same name.
Change you query little bit like below
$sql = "SELECT *, friends.id as friendsID FROM users
INNER JOIN friends
ON users.id = friends.id
WHERE (friends.user1='$u' OR friends.user2='$u' AND friends.accepted='1')";
Now you will have id' as User Id andfriendsID` as Friend's ID

PHP/MYSQLi SQL SELECT on multiple table and return the result as json object

I am building user status app where other can comment. I fetch the json result through ajax and then display it in my ap. however my problem is when i run the query it return only one run for each replies even though there are multiple replies for each status. Honestly i dont know whether the problem is from the PHP loop or it is from the SQL queries it self. I have battling with this since two days now and have search other Stackoverflow question for help but still. I will be glad if anyone can help me. Thank you.
User status are saved in the Status table and all replies on each status is saved in the replies table.
These are my tables
Users Table = gcm_users
id
name
date
Status Table = gcm_status
id
userID
status
Replies Table = gcm_status_replies
id
statusID
userID
replies
This is my sql statement
$sqlSelect = ( 'SELECT gcm_status.status,
gcm_status.id,
gcm_status.userID,
gcm_status_replies.id,
gcm_status_replies.statusID,
gcm_status_replies.userID,
gcm_status_replies.message,
gcm_users.id,
gcm_users.name
FROM gcm_users INNER JOIN gcm_status
ON gcm_users.id = gcm_status.userID
INNER JOIN gcm_status_replies
ON gcm_status.id = gcm_status.id'
array(''), $conn);
PHP Loops is
foreach ($sqlSelect as $row) {
$respohnds = json_encode($row);
echo $respohnds;
}
I really need to help.
You're generating a separate json object for each row, and returning them one by one.
Maybe you should do this instead to return a single json object encoding your whole result set as an array.
$respondhs = array();
foreach ($sqlSelect as $row) {
$respohnds[] = json_encode($row);
}
echo $respohnds;

Foreach or Inner join? -- that is the PHP question

I have 2 tables. One (artWork) with all the data I want to pull from, including 2 cols of id's. The other (sharedWork) has the same 2 id cols that are also in the first -- but none of the essential data I want to echo out. Objective: use the id's in both table to filter out row in the first (artWork). See below in the code what I tried that didn't work
I also tried to figure out an inner join that would accomplish the same. No luck there either. Wondering which would be the best approach and how to do it.
thanks
Allen
//////// Get id's first ///////////
$QUERY0="SELECT * FROM artWork WHERE user_id = '$user_id' ";
$res0 = mysql_query($QUERY0);
$num0 = mysql_num_rows($res0);
if($num0>0){
while($row = mysql_fetch_array($res0)){
$art_id0 = $row['art_id'];
}
}
$QUERY1="SELECT * FROM shareWork WHERE user_id = '$user_id' ";
$res1 = mysql_query($QUERY1);
$num1 = mysql_num_rows($res1);
if($num1>0){
while($row = mysql_fetch_array($res1)){
$art_id = $row['art_id'];
}
}
$art_id2 = array_merge($art_id0, $art_id1);
foreach ($art_id2 as $art_id3){
$QUERY="SELECT * FROM artWork WHERE art_id = '$art_id3' ";
// echo "id..".$art_id0;
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$art_title = $row['art_title'];
$art_id = $row['art_id'];
etc................and so on
.........to....
</tr>";
}
}
}
Don't query your database inside a loop unless you absolutely have to.
Everytime you query the database, you're using disk I/O to read through the database and return your record. Disk I/O is the slowest read on a computer, and will be a massive bottleneck for your application.
If you run larger queries upfront, or at least outside of a loop, you will hit your disk less often, improving performance. Your results from larger queries will be held in memory, which is considerably faster than reading from disk.
Now, with that warning out of the way, let's address your actual problem:
It seems you're trying to grab records from artWork where the user is the primary artist, or the user was one of several artists to work on a group project. artWork seems to hold the id of the primary artist on the project whereas shareWork is probably some sort of many-to-many lookup table which associates user ids with all art projects they were a part of.
The first thing I should ask is whether or not you even need the first query to artWork or if the primary artist should have a record for that art_id in shareWork anyway, for having worked on the project at all.
If you don't need the first lookup, then the query becomes very easy: just grab all of the users art_ids from shareWork table and use that to lookup the his or her records in the main artWork table:
SELECT artWork.*
FROM artWork
WHERE art_id IN
(SELECT art_id
FROM shareWork
WHERE user_id = $user)
If you do need to look in both tables, then you just add a check in the query above to also check for that user in the artWork table:
SELECT artWork.*
FROM artWork
WHERE
user_id = $user
OR art_id IN
(SELECT art_id
FROM shareWork
WHERE user_id = $user)
This will get you all artWork records in a single query, rather than.. well, a lot of queries, and you can do your mysql_fetch_array loop over the results of that one query and be done with it.

Categories