MySQLi select from two table with limit - php

I have been try to combine two tables from mysql database, the two tables are status and status_reply both have the same columns number and name, that is id, account_name, author, postdate, data Please a help will be appreciated.
$limit = "LIMIT 0, 10";
$query = mysqli_query($db_conx, "(SELECT * `status` as type from status WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)
UNION (SELECT * `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)");
//$query = mysqli_query($db_conx, "SELECT * FROM status WHERE data LIKE '%$tag%' ORDER BY postdate DESC $limit");
$statusnumrows = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$statusid = $row["id"];
$account_name = $row["account_name"];
$author = $row["author"];
$postdate = $row["postdate"];
$data = $row["data"];
$data = nl2br($data);
$data = str_replace("&","&",$data);
$data = stripslashes($data);
$statuslist .= '<div id="status_'.$statusid.'" class="status_boxes"><div><b>Ivotised by '.$author.' '.$postdate.':</b>
<article>'.$data.'</article>
</div></div>';
}

Use backquotes ` for field names instead of straight quotes '
Don't forget to quote $tag to protect from an SQL injection: mysqli_real_escape_string
Remember, that is you want to search literally for LIKE wildcard characters "%", "_" as well as backslash. You need to escape them too, using: $tag = addcslashes($tag, '\%_');
$limit = "LIMIT 0, 10";
$query = mysqli_query($db_conx, "
(SELECT `status` as type from status WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)
UNION
(SELECT `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)");

I realized that I have to remove the type in both status and status_reply as references to the tables and identified each of the columns by their names. Am curious about it too!
$query = mysqli_query($db_conx, "
(SELECT id, account_name, author, postdate, data from status WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)
UNION
(SELECT id, account_name, author, postdate, data from status_reply WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)");

Related

MySQL/PHP - Display Recent Date

I was able to apply this line onto phpMyAdmin and it worked just fine.
SELECT id, date_format(`date`, '%m.%d.%Y') as `date` FROM TABLE ORDER BY date DESC LIMIT 1
The problem is that when I added the rest of the code, the recent date shows up blank on the webpage. Am I missing something in this code?
<?php
$query = "SELECT id, date_format(`date`, '%m.%d.%Y') as `date` FROM TABLE ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
echo "$date";
?>
Any help is appreciated. Thank you.
. Try this
$query = "SELECT id, date_format(`date`, '%m.%d.%Y') as `date` FROM TABLE ORDER BY. date DESC LIMIT 1";
$result = mysql_query($query);
$r = mysql_fetch_assoc($result);
$date = $r['date'];
echo "$date";
You didn't set $date variable. You need to use mysql_fetch_array function for your $result variable.
Ex:
`
$query = "SELECT id, date_format('date', '%m.%d.%Y') as 'date' FROM TABLE ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row); }
`

group rows, count grouped rows and order by grouped rows

I want to make an analytics system for a website and I am trying to row accesed urls from a db, group by url, count grouped rows and order DESC by number of grouped rows.
$sql = "SELECT COUNT(*) FROM (SELECT DISTINCT url FROM analytic) ORDER by (SELECT DISTINCT url FROM analytic)";
$countQry = mysqli_query($link, $sql);
while($arr = mysqli_fetch_array($countQry)) {
?>
<?=$arr['url']?>
<?
}
?>
thanks
Try using a GROUP BY:
SELECT url, COUNT(url) AS theCount
FROM analytic
GROUP BY url
ORDER BY theCount DESC
Here is PHP code for you to use:
$sql = "SELECT url, COUNT(url) AS theCount FROM analytic GROUP BY url ORDER BY by theCount DESC";
$countQry = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($countQry, MYSQLI_ASSOC)) {
echo $row['url'], ", ", $row['theCount'];
}

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

How to use a Union properly with Order BY?

The code I have below joins 5 tables and then is suppose to sort by date_timed_added. The query worked perfectly if i only join 4 tables. For some reason after the 4th table, its giving me issues. The issue is that it sorts and displays the 5th table first and then the rest follow. How can i fix it so that it sorts date_time_added properly by querying all the other tables?
//$sid is a variable that is drawn from DB
$sql = "select `client_visit`.`visit_id`, `client_visit`.
`why_visit`, `client_visit`.`date_time_added`, `client_visit`.
`just_date`, `client_visit`.`type` from `client_visit` where
`client_visit`.`system_id` = '$sid' and `client_visit`.
`added_by` = '$sid'
UNION
select `client_notes`.`note_id`, `client_notes`.`note_name`,
`client_notes`.`date_time_added`, `client_notes`.`just_date`
, `client_notes`.`type` from `client_notes` where `client_notes`.
`added_by` = '$sid'
UNION
select `client_conditions`.`med_id`, `client_conditions`.`med_name`,
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,
`client_conditions`.`type` from `client_conditions` where
`client_conditions`.`system_id` = '$sid' and `client_conditions`.
`added_by` = '$sid'
UNION
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`,
`client_stats`.`date_time_added`, `client_stats`.`just_date`,
`client_stats`.`type`
from `client_stats` where `client_stats`.`system_id` = '$sid'
and `client_stats`.`added_by` = '$sid'
UNION
select `client_documents`.`doc_id`, `client_documents`.`doc_name`,
`client_documents`.`date_time_added`, `client_documents`.`just_date`,
`client_documents`.`type` from `client_documents` where `client_documents`.
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid'
ORDER BY `date_time_added` DESC LIMIT $startrow, 20";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
//Just using these two variables i can display the same row info
//for all the other tables
$stuffid = htmlspecialchars($row['visit_id']);
$title = htmlspecialchars($row['why_visit');
}
}
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/union.html
If you want to order the ENTIRE result set, the ORDER BY clause must be placed on the LAST query in the UNION, with each query being bracketed.
(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...
sth like this should do.
SELECT Tbl1.field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) Tbl1
ORDER BY Tbl1.field1

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