Cross table query - php

I'm running a query with retrieves user posts. The table Posts has a column with the name of the User who submitted the post, also another table called User has a list of usernames and avatars.
I need to look up in each post for 'User' on table Users and if there is a match echo column "Avatar" from this table.
$result = mysql_query("SELECT * FROM Posts WHERE MATCH (City) AGAINST ('$city2') ORDER by `Comments` DESC LIMIT $limit_posts OFFSET $first_post");
while($row = mysql_fetch_array( $result )) { ?>
<div class='item'>
<?php echo $row['Text']; ?>
<? }

$result = mysql_query("
SELECT
Posts.*,
Users.Avatar
FROM
Posts
INNER JOIN
Users
ON
Users.ID = Posts.User
WHERE
MATCH (Posts.City) AGAINST ('$city2')
ORDER BY
Posts.`Comments` DESC
LIMIT
$limit_posts
OFFSET
$first_post
");
while($row = mysql_fetch_array( $result )) { ?>
<div class='item'>
<?php echo $row['Text']; ?>
<?php echo $row['Avatar']; ?>
<? }

This is just a basic table join right?
SELECT USERS.AVATAR, POSTS.TEXT
FROM USERS INNER JOIN POSTS ON USERS.ID = POSTS.USER
Will return a list of user avatar and post text for every user

Related

Loop through two while arrays

I am making this post system with like button and count for a social networking site.
My end goal is to loop through these two sets of results together. So that the like counts goes with the individual posts as they loop. The posts and likes are in desc order. Everything matches except I can't get these while fetch results to loop together.
Post loop
<table class="postborder">
<?php
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
?>
<div id="newpost">
<tr>
<td id="userpost"><?php echo $row['username']; ?> </td>
</tr>
<tr>
<td>
<hr id="hrline">
<img id="newimgpost" src="data:image/jpeg;base64,<?php echo base64_encode($row['name']); ?>" height="500" width="500" class="img-thumnail" />
</td>
<tr>
<td id="textpost">
<?php echo $row['textpost']; ?>
</td>
</tr>
<tr>
<td id="likebutton">
<?php } ?>
</div>
</table>
Like count loop
<?php
//index.php
//session_start();
//SESSION['userid'] = (int)3;
$connect = mysqli_connect("localhost", "root", "", "snazzer");
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
if (!$result2) {
printf("Error: %s\n", mysqli_error($connect));
exit();
}
while($row = mysqli_fetch_array($result2))
{
echo '<h3>'.$row["textpost"].'</h3>';
echo '
LIKE';
echo '<p>'.$row["likes"].' People like this</p>';
if(count($row["liked"]))
{
$liked = explode("|", $row["liked"]);
echo '<ul>';
foreach($liked as $like)
{
echo '<li>'.$like.'</li>';
}
echo '</ul>';
}
}
if(isset($_GET["type"], $_GET["id"]))
{
$type = $_GET["type"];
$id = (int)$_GET["id"];
if($type == "postid")
{
$query = "
INSERT INTO likes (userid, postid)
SELECT {$_SESSION['userid']}, {$id} FROM tbl_images
WHERE EXISTS(
SELECT id FROM tbl_images WHERE id = {$id}) AND
NOT EXISTS(
SELECT id FROM likes WHERE userid = {$_SESSION['userid']} AND postid = {$id})
LIMIT 1
";
mysqli_query($connect, $query);
header("location:profile.php");
}
}
?>
I believe you could run two queries together. It's fairly simple; just separate each query with semicolon:
$query = "SELECT * FROM tbl_images ORDER BY id DESC;
SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Or separate the variable by incrementing values, you can read their documentation which explains it here.
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$query .= "SELECT tbl_images.id, tbl_images.textpost, COUNT(likes.id) as likes, GROUP_CONCAT(users.name separator '|') as liked FROM tbl_images LEFT JOIN likes ON likes.postid = tbl_images.id LEFT JOIN users ON likes.userid = users.userid GROUP BY tbl_images.id ORDER BY id DESC";
Then run your code as you normally would except you change mysqli_query to mysqli_multi_query:
$result = mysqli_multi_query( $connect, $query );
while($row = mysqli_fetch_array( $result )) {
//... code your table here ...//
}
You can also the Object-Oriented method which works pretty well:
$result = $connect->multi_query( $query );
But of course both methods should work fine. Do keep in mind, you may be vulnerable to SQL Injections with mysqli_multi_query. This is PHP's official warning:
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
Considerations
You could always save both results from your while loop in an array and run them in a foreach loop or have them output individually as $array['key']. Which would be a simple workaround to your queries:
<?php
// first query
$query1 = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query1);
while($row = mysqli_fetch_array($result)) {
$array1[] = $row;
}
// second query
$query2 = "
SELECT tbl_images.id, tbl_images.textpost,
COUNT(likes.id) as likes,
GROUP_CONCAT(users.name separator '|') as liked
FROM
tbl_images
LEFT JOIN likes
ON likes.postid = tbl_images.id
LEFT JOIN users
ON likes.userid = users.userid
GROUP BY tbl_images.id
ORDER BY id DESC
";
$result2 = mysqli_query($connect, $query2);
while($row = mysqli_fetch_array($result2)) {
$array2[] = $row;
}
Once you have those records setup you can now use $array1 and $array2 to setup your table.
To get their keys and setup you can use print_r or var_dump and you will be able to see key => value pairs:
print_r( $array1 );
echo '<br />';
print_r( $array2 );

Multiple Select query in while loop

963 rows in user table
872 rows in videos table
In user table (fbid,name) are column names
In video table (fbid,etc..) are colum names.
Using below query, I am fetching name from user table by providing fbid from video table. Below query is only returning 791 rows but it should return 872 instead.
<?php
$counter = 1;
$q = "SELECT * FROM videos GROUP BY fbid ORDER BY score DESC, id ASC";
$r = mysqli_query($conn,$q);
if(mysqli_num_rows($r)>0):
while($row = mysqli_fetch_assoc($r)):
$fbid=$row['fbid'];
$q1 = "SELECT name FROM users WHERE fbid=".$fbid."";
$r1 = mysqli_query($conn,$q1);
while($row1 = mysqli_fetch_assoc($r1)):
$name=$row1['name'];
?>
<?php
$counter++;
endwhile;
endwhile;
endif;
?>
SELECT v.*
, u.name
FROM videos v
JOIN users u
ON u.fbid = v.fbid
ORDER
BY v.score DESC
, v.id ASC;
I modified the code for your inquiry
<?php
$counter = 0;
$q = "SELECT DISTINCT * FROM `videos` ORDER BY `fbid` ASC";
$r = mysqli_query($conn,$q);
if(mysqli_num_rows($r)>0):
while($row = mysqli_fetch_assoc($r)):
$fbid=$row['fbid'];
$q1 = "SELECT * FROM `user` WHERE `fbid`= $fbid ";
$r1 = mysqli_query($conn,$q1);
while($row1 = mysqli_fetch_assoc($r1)):
$name=$row1['nombre'];
echo $name . "<br/>;
?>
<?php
$counter++;
endwhile;
endwhile;
endif;
echo "Total " .$counter;
?>
if you go 791 results may be because some video fbid table is not in the table check how many users this query
SELECT count(fbid) FROM `videos` where fbid NOT IN(SELECT fbid FROM `user`);

trying to form SQL join on several tables

So Im trying to figure out how to do this with 1 query if possible. Here is what I have with several queries
$file_url = 'http://'.$cms.'/filemanager/gallery';
$link_url = '/our-process/gallery/';
include 'inc/config.php';
function gallerySafeName($var){
$var = strtolower(preg_replace('([^a-zA-Z0-9_])','-',$var));
return $var;
}
$galleryimages = array();
$sql = "SELECT * FROM `cms_gallery_categories` ORDER BY RAND() LIMIT 3";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($result)){
$sql1 = "SELECT * FROM `cms_gallery_images` WHERE `image_id` = ".$row['category_image_id'];
$result1 = mysqli_query($con,$sql1);
while ($row1 = mysqli_fetch_array($result1)){
$sql2 = "SELECT * FROM `cms_gallery` WHERE `gallery_id` = ".$row1['gallery_id'];
$result2 = mysqli_query($con,$sql2);
while ($row2 = mysqli_fetch_array($result2)){
print '<li>
<a href="'.$link_url.$row['category_name'].'/'.$row2['gallery_name'].'/'.gallerySafeName($row1['image_caption']).'/">
<img width="210" height="133" border="0" src="'.$file_url.'/'.$row['category_name'].'/'.$row2['gallery_name'].'/'.$row1['image_name'].'" />
</a>
</li>';
}
}
}
Im trying to get 3 random entries from the gallery category and the image assigned to represent that category. Then get the gallery name and then the image name to form a img src and link. My table structure is as follows
-cms_gallery_categories
category_id
category_title
category_name
category_image_id
-cms_gallery
gallery_id
gallery_title
gallery_name
category_id
-cms_gallery_images
image_id
image_name
image_caption
gallery_id
Images belong to galleries, and galleries belong to categories
SELECT GC.*, G.*, I.*
FROM cms_gallery_categories GC
INNER JOIN cms_galleries G ON (G.category_id = GC.category_id)
INNER JOIN cms_gallery_images I ON (I.gallery_id = G.gallery_id)
ORDER BY RAND() LIMIT 3
You will want to limit your fields to what you need only. From what I can see in your code, it's this:
SELECT GC.category_name, G.gallery_name, I.image_caption FROM...
More info
http://www.w3schools.com/sql/sql_join.asp
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
http://www.tutorialspoint.com/sql/sql-using-joins.htm

Counting Number Of Classifieds In Category

I have a table categories that has: id, name, subcategory_id, parent_id. Another table classifieds that has: classified_id, title, description, category_id.
I am trying to to pull numbers of classifieds in each category. So it will look like this.
Accessories(10)
Cars(15)
Dating(12)
I gave it a try like this:
enter $catquery = mysql_query("SELECT * FROM categories WHERE sub_id = '0' ORDER BY name ASC"); here
enter $catrows = mysql_num_rows($catquery); here
enter $catrows = mysql_num_rows($catquery); here
enter $query = "SELECT category_id, COUNT(title) AS `total` FROM classifieds WHERE classified_id = 'category_id' "; here
enter $result = mysql_query($query); here
enter while($row = mysql_fetch_assoc($result)){ $num_items_in_category[$row['category_id']] = $row['total']; here
enter } echo "<li><a href='category.php?cat=".$row['id']."'>".$row['name']. $row['total']. "</a></li>"; here
Thanks fellas
You should be able to accomplish what you're looking for by joining the 2 tables.
SELECT a.name, count(*) as cnt
FROM categories a
join classifieds b
on a.id = b.category_id
group by a.name
COUNT is an aggregate function, so you can get all of the counts at once.
I believe what you are looking for is
$query = "SELECT category-id, COUNT(title) AS `total` FROM classifieds WHERE classified-id = 'category-cat' GROUP BY category-id";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$num_items_in_category[$row['category-id']] = $row['total'];
}
This will give you associative array with the count of records for each category-id

MYSQL like a join but only need the newest row?

I want to do the following but in one query:
$query = mysql_query("SELECT name FROM tbl_users WHERE category = '1'");
while($row = mysql_fetch_assoc($query))
{
$query2 = mysql_query("SELECT datecreated
FROM tbl_comments
ORDER BY datecreated DESC LIMIT 1");
$row2 = mysql_fetch_assoc($query2);
echo $row['name'] . " > " . $row2['datecreated'] ."<br />";
}
There is a user table and a comments table, I want to display a list of users and the date of the last comment next to them?
Is this possible in a single query?
You can do so using the following SQL:
SELECT name,
(
SELECT datecreated
FROM tbl_comments
WHERE tbl_users.user_id = tbl_comments.user_id
ORDER BY datecreated LIMIT 1
)
FROM tbl_users
WHERE category = '1';
OR using:
SELECT tbl_users.name, MAX(datecreated) AS latestcomment
FROM tbl_users LEFT JOIN tbl_comments ON (tbl_users.user_id = tbl_comments.user_id)
GROUP BY tbl_users.name;

Categories