Hi i have a social networking website.
what i want it to do is pull out my friends status updates.
basically what it does is i have a mysql query that pulls out all of my friends and in that while loop there is another mysql query that pulls out the status's from my friends.
i want it to be in order of date but since its one while loop in another what it does is pull out all status's from friend 1 then 2 then 3 and not in order by date. i even tried ORDER BY DATE but that just ordered it by date within the friend..
my thought is that i could putt it all in an array and friends is one thing and the values is the stats. then just sort by values would this work and how could i do it.
the friend and stats are in two differants tables
THANKS SO MUCH
CODE:
$friendssql = mysql_query("SELECT * FROM friends WHERE sender='$id'");
while($row = mysql_fetch_object($friendssql)) {
$friendid = $row-> accepter;
$frsql = mysql_query("SELECT * FROM myMembers WHERE id='$friendid'");
while($rowa = mysql_fetch_object($frsql)) {
$ufirstname = $rowa-> firstname;
$ulastname = $rowa-> lastname;
}
$blabsql = mysql_query("SELECT * FROM blabbing WHERE mem_id='$friendid' ORDER BY blab_date DESC");
while($rowb = mysql_fetch_object($blabsql)) {
$blab = $rowb-> the_blab;
$blabd =$rowb-> blab_date;
$ucheck_pic = "members/$friendid/image01.jpg";
$udefault_pic = "members/0/image01.jpg";
if (file_exists($ucheck_pic)) {
$blabber_pic = "<img src=\"$ucheck_pic\" width=\"50px\" border=\"0\" />"; // forces picture to be 100px wide and no more
} else {
$blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more
}
Once you've put your data into the array, you could take a look at some of the various array sorting functions in PHP: http://php.net/manual/en/array.sorting.php
why not do it all in one query? this is psuedo sql, so you'll have to modify with your real tables and relationships.
select f.name,s.statustext
from friends f
inner join status s
on s.friend_id = f.id
inner join myfriends mf
on mf.friend_id = f.id
where mf.myid = 'myid'
order by f.name, s.datestamp
or something similar.
Related
I'm trying to write a php code to select form tables:
books
images
Some books does not have an image, so I want to skip it and select another book.
I have wrote this code but it does not work with me perfectly.
Now I'm getting only 5 records! it must be 6 as I limited in the book select query.
$slider_sql = "select * from books limit 6";
$slider_result = $conn->query($slider_sql);
while($slider_row = $slider_result->fetch_assoc()) {
extract($slider_row);
$img_sql = "SELECT big_img FROM images WHERE book_id = '$id'";
$img_rs = $conn->query($img_sql);
$img_row = $img_rs->fetch_assoc();
if ($img_rs->num_rows == 0)
continue; //--> here I want to start while again to select another book.
echo $book_name.'<br>';
echo $img_row['big_img'].'<br>';
}
Thanks for your help and time!
Instead of having a sub-query in a loop (which is nearly ALWAYS a bad idea!), use a JOIN instead, which simplifies it to one query instead of two. Then set a condition that big_img should not be empty. This guarantees that you will only find rows where there's an image matching the book. LIMIT will still only ensure the return of 6 rows. <> in MySQL is the same as !=.
$slider_sql = "SELECT b.book_name, i.big_img
FROM books b
JOIN images i
ON i.book_id=b.id
WHERE i.big_img <> ''
LIMIT 6";
$result = $conn->query($slider_sql);
while ($row = $result->fetch_assoc()) {
echo $row['book_name'].'<br>';
echo $row['big_img'].'<br>';
}
MySQL JOIN
I'm getting terribly slow results from the following code. I've been trying to troubleshoot it for hours but with no results. I've included only the relevant code.
Edit:
I am trying to select an id from a database and then use that id to get all the images associated with it. I am then narrowing that group of images down to one. Once I have that image I am resizing it through an external file.
I've tried removing various parts of the code to identify the problem and it seems as if the slow down is being caused by the second query but I am not sure why. Thanks for your help.
$getworks = mysql_query ("SELECT a_id from artists where display_works = '1' and active = '1' order by project_year desc, fullname desc");
while ($getworksrow = mysql_fetch_assoc($getworks)){
$totalimages=1;
$addstyle = "";
$id = $getworksrow["a_id"];
$getimages = mysql_query ("SELECT a_id, image_id from images where a_id = '". $id ."' order by position asc LIMIT 1");
$getimagesrow = mysql_fetch_assoc($getimages);
foreach ($getimagesrow as $getimagesrows){
extract($getimagesrow);
if($totalimages > 1){ $addstyle = 'style="display:none;"'; }
else {
$myimagename = "http://artist.com/$a_id/images/$image_id" . "_large.jpg";
list($width, $height, $type, $attr) = getimagesize("$myimagename");
$myimagename = "http://artist.com/artists/resize.php/$a_id/images/$image_id" . "_large.jpg?resize(157x2000)";
if($getworksrows["layout"] == "vert"){$pl = "_vertical";}else if($getworksrows["layout"] == "website"){$pl = "-s";}else if($getworksrows["layout"] == "video"){$pl = "_video";}else{$pl = "_horizontal";}
echo "<li class='thumbnail_container' $addstyle> <a class='thumbnail' href=\"../works$pl.php?a_id=" . $getworksrows["a_id"] . "\"><span><img src=\"$myimagename\" /></span>\n</a></li>\n";
}
$totalimages++;
}
}
It's a a big performance overhead to execute queries like this specially when parent query have large no. of records.
You should use join artists table with images table and get all data by single query.
Later on make 2D array of per artists and images. and loop according to 2D array to display data
Below is join query you should use:
SELECT * from artists as art
left join images as img on art.a_id=img.a_id
where display_works = '1' and active = '1'
order by project_year desc, fullname desc
In While make data array:
while ($getworksrow = mysql_fetch_object($getworks)){
$data['a_id']['img_id']=$getworksrow->image; //Make 2D array
........
........
}
looping and display data :
foreach($data as $id=>$images)
{
foreach($images as $val){
// Do your stuff for displaying data
}
}
So please do required changes.
I just need help refining this script to give me the values from both tables joined on the ID.
Basically I want the ID from both tables and then be able to get the other values from both tables based on the IDs (if need be) and display them in a loop.
The code I have is below but won't work.
$select = myQ("SELECT * FROM users a WHERE EXISTS (SELECT 1 FROM `videos` b WHERE a.id = b.id GROUP BY b.id HAVING count(*) > 1) ");
$i=0;
while ($row = myF($select)) {
$resultsLoopArray[$i]["videos.id"] = $row["id"];
$resultsLoopArray[$i]["videos.vid"] = $row["vid"];
$resultsLoopArray[$i]["users.username"] = $row["username"];
$i++;
}
if (isset($resultsLoopArray)) {
$tpl->Loop("searchResultsLoop", $resultsLoopArray);
}
For now all I need is the username from the users table, the id and video id from the video table.
Can someone help by chance?
you question is bit confusing me..
As for my understanding I am posting this soultion..
If you have two tables users , videos then .
$sql = "SELECT users.username , videos.* from users, videos where users.user_id = videos.user_id";
this query will fetch all record from users and videos table where user id is present in videos tables ...
I've got
a users table named "members"
a rooms table named "rooms"
a table that associates the user id to the ids of the rooms "membersRooms"
I should write a loop that prints a dropdown for each user with all the rooms, but that adds the attribute "selected" to rooms associated with the user
What's wrong with this loop?
$members = mysql_query("SELECT * FROM members ");
$rooms = mysql_query("SELECT * FROM rooms");
while($member = mysql_fetch_array($members)){
echo("<select>");
$roomsOfUser = mysql_query("SELECT roomID FROM membersRooms WHERE userID=".$member["id"]);
$cuArray = mysql_fetch_array($roomsOfUser);
while($room = mysql_fetch_array($rooms)){
if(in_array($room["id"],$cuArray,true))
echo("<option selected='selected'>".$room["roomName"]."</option>");
else
echo("<option>".$class["roomName"]."</option>");
}
echo("</select>");
}
To make this a little easier on you, you could try utilizing left and right joins on your database. This would significantly reduce your server load and still allow you to do the same functionality.
I believe, if I'm reading your database structure right, that you'ld want something along the lines of:
SELECT members.id as memberID, rooms.id as roomID, rooms.roomName, membersRooms.roomID as memberRoom
FROM members
LEFT JOIN membersRooms
ON members.id = membersRooms.userID
RIGHT JOIN rooms
ON membersRooms.roomID = rooms.id
Then in PHP you should be able to just keep track of when your memberID changes, and when it does, start a new select. If I didn't totally bungle that SQL (which I might have) then the resulting rows should look something like:
memberID | roomID | roomName | memberRoom
1 1 foo 1
1 2 bar 1
2 1 foo 1
2 2 bar 1
So on your loop iteration you would use roomID and roomName to build your select, and if RoomID matched memberRoom then you would select that row.
$rooms query while is dead
while runs once time in while
put this $rooms = mysql_query("SELECT * FROM rooms"); query line
in first while
OK, so you need information from 3 tables - members, rooms, and membersRooms. The rows from members and membersRooms line up 1:1, so we can get both of those with 1 query.
This method will minimize the number of queries needed - if you ever see yourself querying the database in a loop, ask yourself if there's a better way.
$member_query = mysql_query("SELECT * FROM members LEFT JOIN membersRooms ON (members.id = membersRooms.userID)");
$room_query = mysql_query("SELECT * FROM rooms");
$rooms = array();
while ($room = mysql_fetch_assoc($room_query))
$rooms[] = $room;
while ($member = mysql_fetch_assoc($member_query)) {
echo '<select>';
foreach($rooms as $room) {
echo "<option value='{$room['roomID']}' ";
if ($member['roomID'] == $room['id'])
echo 'selected="selected"';
echo ">{$room['roomName']}</option>";
}
echo '</select>';
}
It's worth noting that if members:rooms is a 1:many relation, you don't need to use a third table to join them - just add a roomId to members, and you're fine.
Mysql query and PHP code that I'm using to get users from the database that meet certain criteria is:
$sql = mysql_query("SELECT a2.id, a2.name FROM members a2 JOIN room f ON f.myid = a2.id
WHERE f.user = 1 AND a2.status ='7' UNION SELECT a2.id, a2.name FROM members a2
JOIN room f ON f.user = a2.id WHERE f.myid = 1 AND a2.status ='7' GROUP BY id")
or die(mysql_error());
while ($r = mysql_fetch_array($sql))
{
$temp[] = '"'.$r[0].'"';
}
$thelist = implode(",",$temp);
The query that follows get the list of members with new galleries by using array from the previous query.
$ft = mysql_query("SELECT id, pic1 FROM foto WHERE id IN ($thelist) AND
pic1!='' ORDER BY date DESC LIMIT 10");
while ($f = mysql_fetch_array($ft))
{
echo $f['id']." - ".$f['pic1']."<br/>";
}
These queries working fine but I need to get the name for every user listed in second query. This data is in the first query in the column name. How can I get it listed beside '$f['id']." - ".$f['pic1']'?
While I might just alter the first query to pull the galleries at the same time, or change the second query to join and get the name, you could keep the same structure and change a few things:
In the loop after the first query when building $temp[], also build a lookup table of user id to user name:
$usernames[$r[0]] = $r[1];
Then in your output loop, use the id (assuming they are the same!) from the second query to call up the user name value you stored:
echo $f['id'] . " - " . $f['pic1'] . " - " . $usernames[$f['id']] . "<br/>";