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
Related
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 );
I have the following 3 tables in my database.
Table: Images
Columns: Image_ID, Title, Description, Author, Date, Path, Rating
Table: Tags
Columns: Tag_ID, Title
Table: TagsConnection
Columns: Image_ID, Tag_ID
In order to get all the images that correspond to a certain tag, I execute this code.
<?php
$tagName = $_SERVER['QUERY_STRING'];
$realTagName = substr($tagName, 1);
$realestTagName = str_replace('%20', ' ', $realTagName);
$sql = "SELECT * FROM tags WHERE tag='$realestTagName'";
$result = mysqli_query($conn, $sql);
$getResult = mysqli_fetch_assoc($result);
$tagId = $getResult['id'];
$sql2 = "SELECT * FROM tagsconnection WHERE tagid='$tagId'";
$result2 = mysqli_query($conn, $sql2);
while ($row = mysqli_fetch_assoc($result2)) {
$imageId = $row['imageid'];
$sql3 = "SELECT * FROM image WHERE id='$imageId'";
$result3 = mysqli_query($conn, $sql3);
$getResult3 = mysqli_fetch_assoc($result3);
echo '<div class="imageContainer">
<h1>'.$getResult3['name'].'</h1>
<a href="imageInfo.php?='.$getResult3["path"].'">
<img class="uploadedImg" src="uploads/'.$getResult3["path"] .'" alt="Random image" />
</a>
</div>';
}
?>
I have this bad feeling that I'm not doing it the way it should be done, so I decided to ask around here and get a few tips and pointers if possible.
Use a join, here's a basic example of how it may look
SELECT * FROM tags
JOIN tagsconnection ON tagsconnection.tagid=tags.id
JOIN image ON image.id=tagsconnection.imageId
WHERE tag=$realestTagName
If you not familiar with joins, here's a good tutorial
https://www.w3schools.com/sql/sql_join.asp
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`);
I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'
I have a very simple query but I need to make another query inside it. I have very little knowledge of SQL and PHP so I want to ask your help.
$result = mysql_query("SELECT * FROM img");
while ($row = mysql_fetch_assoc($result))
{
$imgName = $row['name'];
$catID = $row['catid'];
// Problem
// Need to get category NAME from category ID
$result2 = mysql_query("SELECT name FROM cat WHERE id = $catID");
while ($row2 = mysql_fetch_assoc($result2))
{
$catName = $row2['name'];
}
echo "Image: $imgName <br />";
echo "Category: $catName";
}
This looks to be a simple JOIN to get the category name. You can use a single query:
SELECT
img.id AS imgId,
img.name AS imgName,
cat.name AS catName
FROM img JOIN cat ON img.catid = cat.id
Replace your initial query with the above, and it will eliminate the need for the inner query.
You could do a simple subquery on this one:
$result = mysql_query("
SELECT name, catid, (SELECT name FROM cat WHERE id = img.catid) AS cat_name
FROM img
");
This should work. You'll see all the img properties of each table in each row and in addition the cat.name value.
SELECT *, cat.name as catname FROM img
INNER JOIN cat
ON cat.id = img.catid