MYSQL like a join but only need the newest row? - php

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;

Related

How can I turn these multiple mysql_querys into 1 query?

I have two tables: users and threads. When a thread is created, it will store the user_id in the table as author_id. I want to display the thread name and the username of its author with the same query. I am currently using two querys as shown:
$query2 = mysql_query("SELECT author_id FROM threads WHERE id = $threadId") or die(mysql_error());
$result2 = mysql_fetch_array($query2);
$author_id = $result2['author_id'];
$query3 = mysql_query("SELECT username FROM users WHERE id = $author_id") or die(mysql_error());
$result3 = mysql_fetch_array($query3);
$author_name = $result3['username'];
<?php
$sql = '
SELECT t.name, u.username
FROM threads t
JOIN users u ON t.author_id = u.id
WHERE t.id = ' . (int)$threadId . '
';
list($thread_name, $author_name) = mysql_fetch_row(mysql_query($sql));
P.S. Mysql php extension is deprecated.
Try this query:
SELECT username
FROM users
WHERE id = (SELECT author_id
FROM threads
WHERE id = $threadId
LIMIT 1)
Note: Limit 1 is not mandatory as id is unique.

select down and up votes for each post php mysql

I have a forum where users can post questions and can upvote and downvote.
I want to get the upvote and downvote of each post.
What i did previously was do that in 3 sets queries.
$data = mysqli_query($con,"select * from posts");
while($row = mysqli_fetch_assoc($data)){
$pid = $row['post_id'];
$up = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM up WHERE post_id = $pid"))['c'];
$down = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM down WHERE post_id = $pid"))['c'];
}
Can anyone show me how can i do these things in one single query because if a get a lot of posts in 1st query then there will be lots of queries to do.
You can use subqueries and put everything in the first query.
This could be a good start :
$data = mysqli_query($con, "select posts.*, " .
"(SELECT COUNT(*) FROM up WHERE post_id = posts.post_id) as totalUp, " .
"(SELECT COUNT(*) FROM down WHERE post_id = posts.post_id) as totalDown " .
"from posts");
while($row = mysqli_fetch_assoc($data)){
// ...
}
you can use corelated subquery for this where upvotes
and downvotes are counted based on the post id
SELECT p.*,
( select count(*) from up where post_id = p.post_id ) as upVotesCount,
( select count(*) from down where post_id = p.post_id ) as downVotesCount,
FROM posts p

mySQL Order by Most Commented and Least Commented

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";

Duplicates in php while loop

I am getting a bunch of id's from the database - for each id, I want to do a mysql query to get the relating row in another table. This works fine although I also need to get similiar data for the logged in user. With the mysql query I am using - it duplicates the logged in user data according to how many id's it originally pulled. This makes sense although isnt what I want. I dont want duplicate data for the logged in user and I need the data to come from one query so I can order things with the timestamp.
<?php
mysql_select_db($database_runner, $runner);
$query_friends_status = "SELECT DISTINCT rel2 FROM friends WHERE rel1 = '" . $_SESSION ['logged_in_user'] . "'";
$friends_status = mysql_query($query_friends_status, $runner) or die(mysql_error());
$totalRows_friends_status = mysql_num_rows($friends_status);
while($row_friends_status = mysql_fetch_assoc($friends_status))
{
$friends_id = $row_friends_status['rel2'];
mysql_select_db($database_runner, $runner);
$query_activity = "SELECT * FROM activity WHERE user_id = '$friends_id' OR user_id = '" . $_SESSION['logged_in_user'] . "' ORDER BY `timestamp` DESC LIMIT 15";
$activity = mysql_query($query_activity, $runner) or die(mysql_error());
$totalRows_activity = mysql_num_rows($activity);
echo "stuff here";
}
?>
You can try this single query and see if it does what you need
$userID = $_SESSION['logged_in_user'];
"SELECT * FROM activity WHERE user_id IN (
SELECT DISTINCT rel2 FROM friends
WHERE rel1 = '$userID')
OR user_id = '$userID' ORDER BY `timestamp` DESC LIMIT 15";
You probably want something like this:
$user = $_SESSION['logged_in_user'];
  $query_friends_status = "SELECT * FROM friends, activity WHERE activity.user_id = friends.rel2 AND rel1 = '$user' ORDER BY `timestamp` DESC LIMIT 15";
You can replace * with the fields you want but remember to put the table name before the field name like:
table_name.field_name
I hope this helps.
<?php
require_once "connect.php";
$connect = #new mysqli($host, $db_user, $db_password, $db_name);
$result = $connect->query("SELECT p.name, p.user, p.pass, p.pass_date_change,p.email, p.pass_date_email, d.domain_name, d.domain_price, d.domain_end, d.serwer, d.staff, d.positioning, d.media FROM domains d LEFT JOIN persons p
ON d.id_person = p.id AND d.next_staff_id_person != p.id");
if($result->num_rows > 1)
{
while($row = $result->fetch_assoc())
{
echo '<td class="box_small_admin" data-column="Imię i nazwisko"><div class="box_admin">'.$row["name"].'</div></td>';
echo '<td class="box_small_admin" data-column="Domena"><div class="box_admin">'.$row["domain_name"].'</div></td>';
}}
?>

PHP coding question

How can I grab the count value from the query MySQL query below using PHP.
Here is My MySQL code.
$dbc = mysqli_query($mysqli,"SELECT COUNT(*) FROM((SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1')
UNION
(SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.friend_id = users.user_id
WHERE users_friends.friend_id = 1
AND users_friends.friendship_status = '1')) as friends");
using SQL_CALC_FOUND_ROWS should simplify things:
$dbc = mysqli_query($mysqli,"SELECT SQL_CALC_FOUND_ROWS users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1'
");
then afterwards do
$rs = mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$rec = $rs->fetch_array();
$count = $rec[0];
This method will return the number of records that match the query, ignoring any LIMIT statement, whereas using $rs->num_rows will only give you the number of records actually returned. Depends which one you want.
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
http://us.php.net/manual/en/mysqli.query.php
Assuming that you are correctly connected to the MySQL server and your query are executed correctly, you can use the following code:
$values = mysql_fetch_row($dbc);
$count = $values[0];
Your query should look like SELECT COUNT(*) as numThings FROM xxx
The numThings is what you will reference in PHP:
$result = mysql_query("SELECT COUNT(*) as `numThings` FROM xxx");
$row = mysql_fetch_assoc($result);
$count = $row['numThings'];

Categories