I have two tables that I need to pull records from (classifieds_items and attachments). The images for the classified items are stored in a different table (attachments) and there can be multiple images for each classified. I need to pull just one image for each classified item. The problem with the statement below is it will duplicate the results with the items thas have multiple images.
$sql = "SELECT *
FROM classifieds_items
JOIN (attachments) ON (attachments.attach_rel_id = classifieds_items.item_id)
WHERE active = 1
AND open = 1
AND date_expiry > ". time()."
AND attachments.attach_rel_module = 'classifieds'
ORDER BY RAND()
LIMIT 4";
$rs = mysql_query($sql);
if(mysql_num_rows($rs)>0) {
while($row=mysql_fetch_array($rs)) {
$dtl_list .="<div class='fclass'>
<span class='fctitle'><a class='albumlnk' href='#'>".stripslashes($row['name']). '</a></span><br />
<img src="uploads/'.stripslashes($row['attach_thumb_location']).'" /><br />
'.stripslashes($row['price'])."
</div>";
}
}
echo $dtl_list;
In mysql you can just add GROUP BY classifieds_items.item_id :
`$sql = "SELECT *
FROM classifieds_items
JOIN (attachments) ON (attachments.attach_rel_id = classifieds_items.item_id)
WHERE active = 1
AND open = 1
AND date_expiry > ". time()."
AND attachments.attach_rel_module = 'classifieds'
GROUP BY classifieds_items.item_id
ORDER BY RAND()
LIMIT 4";`
Related
I am working on an image gallery system, and I want to know how to limit/show all image uploaded into the gallery/database table. I normally don't know how this is done so I usually use a number greater than the number of columns in the database to show all my columns. I will love to know how this is done in other to change my method of doing this.
HERE IS MY CODE BELOW;
<?php
$image_id = $the_image = $image_des = $time_uploaded = "";
$gallery = mysqli_query($connect, "SELECT * FROM gallery ORDER BY time_uploaded DESC LIMIT 9000");
while ($pick = mysqli_fetch_array($gallery, MYSQLI_BOTH)) {
$image_id = $pick['id'];
$the_image = $pick['image'];
$image_des = $pick['description'];
$time_uploaded = $pick['time_uploaded'];
echo '<div class="nicdark_margin100">';
echo '<img alt="" class="nicdark_radius nicdark_opacity" src="../img/gallery/'.$the_image.'" width="100" height="100" /> ';
echo ' </div>';
}
?>
MySQL doesn't require a LIMIT field in the query. So to get all results
SELECT * FROM gallery ORDER BY time_uploaded DESC
However, if you're trying to do pagination, you can combine LIMIT and OFFSET
## First Page of 25 images
SELECT * FROM gallery ORDER BY time_uploaded DESC LIMIT 25 OFFSET 0
## Second Page of 25 images (offset by 25)
SELECT * FROM gallery ORDER BY time_uploaded DESC LIMIT 25 OFFSET 25
For more info, see
https://www.w3schools.com/php/php_mysql_select_limit.asp
I have 2 tables userdatafiles & users, where i merge the 2 tables together based on common ID, to find the corresponding works attached to the ID, the following PHP code i have retrieve the works from the user, it works fine as i only want to show 1 work per user, but if a user have 2-3 works for example, it will also display the different works out..
PHP
<?php
include 'dbAuthen.php';
$sql = 'SELECT * FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Specialisation = "Painting"';
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$links[] = array(
"links" => $row["Link"],
"caption" => $row["Name"],
);
}
shuffle($links);
echo json_encode($links);
} else {
echo "0 results";
}
?>
the above code works if i only uploaded 1 work per user, what should i do to improve the code so that if a user have multiple works, it will only display a random work among the many that user has? Thanks..
use rand() for random display and set limit to 1 so you will get one random record
ORDER BY RAND() LIMIT 1
so your query will be:
$sql = 'SELECT * FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Specialisation = "Painting" ORDER BY RAND() LIMIT 1';
Use DISTINCT to eliminate repeating userid:
$sql = 'SELECT DISTINCT(users.UserID),name,link FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Specialisation = "Painting" ORDER BY RAND()';
or use GROUP BY:
$sql = 'SELECT users.UserID,name,link FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Specialisation = "Painting" GROUP BY UserID ORDER BY RAND()';
I've been pondering this for some time and thought I would ask some people that are knowledgeable of MySQL and even PHP. Let's say you have a query that gets dynamic information about an article. You also have several tables associated with the articles such as comments and categories. Let's say that on a page of article results you would like to get information such as the number of comments and what category the article is in. Which method would load faster?
One Large Query:
$query = "
SELECT
a.article_id, a.title, a.description, a.category_id
com.comment_id, com.article_id, COUNT(com.article_id) AS num_comments
cat.category_id, cat.title AS cat_titleca
FROM articles AS A
LEFT JOIN categories AS cat ON (a.category_id = cat.category_id)
LEFT JOIN comments AS com ON (a.article_id = com.comment_id)
GROUP BY a.article_id
ORDER BY a.article_id DESC
LIMIT 10";
if($query = mysql_query($query)){
if(mysql_num_rows($query) > 0){
while($article=mysql_fetch_assoc($query)){
echo $article['title'].' has '.$article['num_comments'].' comments and is in the category '.$article['cat_title'].'.';
}
}
}
Or to use several smaller queries:
<?php
$query_articles = "
SELECT
article_id, title, description, category_id
FROM articles
ORDER BY article_id DESC
LIMIT 10";
if($query_articles = mysql_query($query_articles)){
if(mysql_num_rows($query_articles) > 0){
while($article=mysql_fetch_assoc($query_articles)){
$query_comments = "
SELECT
comment_id, article_id
FROM comments
WHERE article_id = ".$article['article_id']."
ORDER BY comment_id";
if($query_comments = mysql_query($query_comments)){
$num_comments = mysql_num_rows($query_comments);
}
$query_cat = "
SELECT
category_id, title
FROM categories
WHERE category_id = ".$article['category_id']."
LIMIT 1";
if($query_cat = mysql_query($query_cat)){
if(mysql_num_rows($query_cat) > 0){
$cat = mysql_fetch_assoc($query_cat);
}
}
echo $article['title'].' has '.$num_comments.' and is in the category '.$cat['title'].'.';
}
}
}
A single query is faster of course, why don't you do benchmark
$time = microtime(true);
//code here
$elapsed = microtime(true) - $time;
echo 'Elapsed time = '.$elapsed;
Here's my current code:
<?php
$tsql = " ";
$tmpsort = " ORDER BY b.flag,b.jjloveb DESC,b.yhtime ";
$rt=$db->query("SELECT a.nickname, a.sex, a.grade, a.photo_s, a.photo_f, a.photo_pass, b.id,b.userid, b.datingkind, b.title, b.price, b.yhtime, b.maidian, b.content, b.bmnum, b.click, b.flag, b.jjloveb, a.birthday, b.province, b.city, b.area, b.age1, b.datingkind, a.identityproof
FROM ".__TBL_MAIN__." a,".__TBL_DATING__." b
WHERE $tsql b.flag>0 AND b.userid=a.id AND a.flag=1
$tmpsort
LIMIT 6");
$total = $db->num_rows($rt);
for($i=0;$i<$total;$i++) {
$rows = $db->fetch_array($rt);
if(!$rows) break;
$Uid = $rows[7];
$Unickname = badstr($rows[0]);
$Usex = $rows[1];
What I want is to fetch the records from the same user id only once.
Thanks very much!
$rt=$db->query("SELECT a.nickname,a.sex,a.grade,a.photo_s,a.photo_f,a.photo_pass,b.id,b.userid,b.datingkind,b.title,b.price,b.yhtime,b.maidian,b.content,b.bmnum,b.click,b.flag,b.jjloveb,a.birthday,b.province,b.city,b.area,b.age1,b.datingkind,a.identityproof FROM ".__TBL_MAIN__." a,".__TBL_DATING__." b WHERE $tsql b.flag>0 AND b.userid=a.id AND a.flag=1 group by b.userid $tmpsort LIMIT 6");
I achieved what I wanted by just inserting a group by. Yeah!
But what about if 2 occurrences per userid is wanted, what approach should be taken?
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.