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`);
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'm trying to order a list of items based on the amount of comments for each topic as shown below:
$page = $_GET['page'];
$query = mysql_query("SELECT * FROM topic WHERE cat_id='$page' LIMIT $start, $per_page");
if (mysql_num_rows($query)>=1)
{
while($rows = mysql_fetch_array($query))
{
$number = $rows['topic_id'];
$title = $rows['topic_title'];
$description = $rows['topic_description'];
//get topic total
$sqlcomment = mysql_query("SELECT * FROM comments WHERE topic_id='$number'");
$commentnumber = mysql_num_rows($sqlcomment);
// TRYING TO ORDER OUTPUT ECHO BY TOPIC TOTAL ASC OR DESC
echo "
<ul>
<li><h4>$number. $title</h4>
<p>$description</p>
<p>$topictime</p>
<p>$commentnumber</p>
</li>
</ul>
";
}
}
else
{
echo "<p>no records available.</p><br>";
}
What would be the best way to order each echo by $num_rows (ASC/DESC values)? NOTE: I've updated with the full code - I am trying to order the output by $commentnumber
The first query should be:
SELECT t.*, COUNT(c.topic_id) AS count
FROM topic AS t
LEFT JOIN comments AS c ON c.topic_id = t.topic_id
WHERE t.cat_id = '$page'
GROUP BY t.topic_id
ORDER BY count
LIMIT $start, $per_page
You can get $commentnumber with:
$commentnumber = $rows['count'];
You don't need the second query at all.
First of all you have error here
echo "divs in order from least to greatest "number = $num_rows"";
It should be
echo "divs in order from least to greatest number = " . $num_rows . "";
And about the most commented try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY column DESC/ASC";
Or if there is not count column try with
$sql = "SELECT * FROM `table` WHERE `id` = '$id' ORDER BY COUNT(column) DESC/ASC";
im trying to select the row quote and author from my table and echo it
my goal is to create a random quote generator and display the actual quote and author.
I have entered 25 quotes in my table with 3 rows (ID, quote, author)
my code is the following and i keep getting the resource id #9 error
<?php
mysql_select_db(name of database);
$quotes = "SELECT author AND quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1";
$result = mysql_query($quotes);
WHILE ($row = mysql_fetch_array($result)):
ENDWHILE;
echo "$result";
?>
please help
First of all, I think you want
<?php
mysql_select_db(name of database);
$quotes = "SELECT author,quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1";
$result = mysql_query($quotes);
WHILE ($row = mysql_fetch_array($result)):
ENDWHILE;
echo "$result";
?>
but I have an additional suggestion
Preload all the quote IDs
CREATE TABLE quoteID
(
ndx int not null auto_increment,
id int not null,
PRIMARY KEY (ndx)
);
INSERT INTO quoteID (id) SELECT id FROM inspirational_quotes;
Now choose based on the id from quoteID table
SELECT B.author,B.quote FROM quoteID A INNER JOIN inspirational_quotes B
USING (id) WHERE A.ndx = (SELECT CEILING(MAX(ndx) * RAND()) FROM quoteID);
This should scale just fine because the return value for #rnd_id comes from a list of ids with no gaps in the quoteID table.
<?php
mysql_select_db(name of database);
$quotes = "SELECT B.author,B.quote FROM quoteID A INNER JOIN "
. "inspirational_quotes B USING (id) "
. "WHERE A.ndx = (SELECT CEILING(MAX(ndx) * RAND()) FROM quoteID)";
$result = mysql_query($quotes);
$row = mysql_fetch_array($result);
echo "$result";
?>
Give it a Try !!!
You cant echo $result as a string
do
WHILE ($row = mysql_fetch_array($result)):
echo $row['author'] . " " . $row['quote'];
ENDWHILE;
?>
You are not echoing the right variable.
echo $row['author'] . ": " . $row['quote'];
Why AND just comma.
SELECT author, quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1
MySQL Select syntax
I suggest you to randomize results by PHP to improve performance. eg.:
$r = mysql_query("SELECT count(*) FROM inspirational_quotes");
$d = mysql_fetch_row($r);
$rand = mt_rand(0,$d[0] - 1);
$r = mysql_query("SELECT author,quote FROM inspirational_quotes LIMIT $rand, 1");
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
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;