PHP - How to Use ORDER BY and GROUP BY together - php

I created a table that contains message, sender, to, time I want group by sender and order by time this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time` GROUP BY `sender`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr ['message'];
echo '</br>';
echo $msg;
}
that shows me this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BYsender' at line 1
So how to fix that problem?
Thanks
Klaus

Note your precedence. After the results have been grouped , it should be ordered.
"SELECT * FROM `table` GROUP BY `sender` ORDER BY `time`"

try this code
$query= mysql_query("SELECT * FROM `table` GROUP BY `sender` ORDER BY `time` ")or die(mysql_error());
// ^^--will be before order
$num = mysql_num_rows($query); // out of the while loop
while($arr = mysql_fetch_array($query)){
$msg = $arr['message'].'<br />';
// ^^--remove space here
echo $msg;
}

how to use self-joins to get the max/min/something-n rows per group.
In your situation, it can be applied to the effect you want like so:
SELECT * FROM
(SELECT group_id, MAX(`yourdate`) AS yourdate FROM tbl_name GROUP BY group_id)
AS x JOIN tbl_name USING (`group_id`,yourdate);

Related

how to use LIKE clause in mysql when using with php

i'm trying to use like in mysql from php and i write this code
$query = mysqli_query($connection, "SELECT * FROM items order by create_at desc where content LIKE '" . $content . "%'")
or die(mysqli_error($connection));
but it says there is an error in my syntax it says like this
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'where content LIKE 'c%'' at line 1
Order BY clause always come in the end, use WHERE clause first and then use ORDER BY
Solution would be this :
SELECT * FROM items where content LIKE 'YourVariable%' ORDER BY create_at DESC
Your PHP code should be:
$query = "SELECT * FROM items where content LIKE '" . $content . "%' order by create_at desc";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
Query clauses sequence should be :
Select
From
join
where
group by
order by
limit
$query = mysqli_query($connection, "SELECT * FROM items order by create_at desc where content LIKE '%.$content.%'") or die(mysqli_error($connection));

Getting an my Sql Error

I am trying to figure out whats wrong in this code but can't make it work
Could you please help me?
$email = $_SESSION['email'];
$email = mysql_real_escape_string($email);
$depst = "SELECT dept FROM stud_reg WHERE email='$email'";
$colls = "SELECT coll FROM stud_reg WHERE email='$email'";
$query="SELECT * FROM stud_reg WHERE coll='$coll' AND dept='$depst'";
$evesel="SELECT id FROM events WHERE `group`='($depst)' AND coll_id='($colls)'";
$studsel="SELECT drs_id FROM event_reg WHERE eve_id='$evesel'";
$query="select * from students WHERE nsite_id='$studsel'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_num_rows($result);
Here's the error i am getting
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'k#***.com')' AND coll_id='(SELECT coll FROM stud_reg WHERE email='k#****' at line 1
PS- All the tables and rows in this code exits
The query you're trying to run is
select * from students WHERE nsite_id='SELECT drs_id FROM event_reg WHERE eve_id='SELECT id FROM events WHERE `group`='(SELECT dept FROM stud_reg WHERE email='$email')' AND coll_id='(SELECT coll FROM stud_reg WHERE email='$email')'''
But this is not going to give you what you expect, even if you did fix up the issues with the quoted strings within quoted strings.
I suspect that instead want to combine that all up as joins, so perhaps something a little like:
SELECT s.*
FROM students AS s
INNER JOIN event_reg AS er
ON er.drs_id = s.nsite_id
INNER JOIN events AS e
ON er.eve_id = e.id
INNER JOIN stud_reg AS grp
ON grp.dept = e.group
AND grp.coll = e.coll_id
WHERE grp.email='$email'
As with any syntax error with SQL, when running from PHP, it's best to get the query working in MySQL first, before trying to plug it in to your application.
"SELECT id FROM events WHERE `group`='".$depst."' AND coll_id='".$colls."'";
Based on the error message you got, I think it just about the single-quotes and double-quotes problem.
This is the corrected query:
$email = $_SESSION['email'];
$email = mysql_real_escape_string($email);
$depst = 'SELECT dept FROM stud_reg WHERE email="$email"';
$colls = 'SELECT coll FROM stud_reg WHERE email="$email"';
$query="SELECT * FROM stud_reg WHERE coll='$coll' AND dept='$depst'";
$evesel="SELECT id FROM events WHERE `group`='($depst)' AND coll_id='($colls)'";
$studsel="SELECT drs_id FROM event_reg WHERE eve_id='$evesel'";
$query="select * from students WHERE nsite_id='$studsel'";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_num_rows($result);
You must be careful on placing quotes in the query.
try like his
$query="select * from students WHERE nsite_id='$studsel';";
And the first queries are never actually executed, and you seem to overwrite the first $query. Either make a 'join', or use subqueries , something like
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
Why don't you try single query. The problem is quotes in your case.
$query = "SELECT * FROM students WHERE nsite_id =
( SELECT drs_id FROM event_reg WHERE eve_id = (
SELECT id FROM events WHERE
`group` = (SELECT dept FROM stud_reg WHERE email = '".$email."')
AND
coll_id = (SELECT coll FROM stud_reg WHERE email = '".$email."')
)
)";
$result=mysql_query($query) or die(mysql_error());
$num=mysql_num_rows($result);

PHP - how to select from a table one query

I got a table that contains ID, Names, message, and time, I want to select from the table only one message query from each ID, Currently I select all the messages, this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo '</br>';
echo $msg;
}
That Shows all messages ordered by time, Is there is a way to select only one message query from each ID?
Thanks,
Klaus
If you want only one message you can use LIMIT like this
SELECT * FROM table ORDER BY time LIMIT 1
Or if you want only one message from some id then you can use GROUP BY
SELECT * FROM table ORDER BY time GROUP BY id
Sure, pretty straightforward
This will fetch all messages given ID:
$id = 10 //Get your id in any way you need
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo $msg;
}
and this will fetch only the first message given ID
$id = 10
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id LIMIT 1")or die(mysql_error());
$row = mysql_fetch_array($query));
if($row){
$msg = $row['message'];
echo $msg;
}else{
echo 'no messages for id '.$id;
}

php MySQL query not returning anything

I'm not sure exactly how to explain what the query does, however the problem isn't entirely with how it's set up, because it does work, in another instance, when I use it as an array, however it's not working when I use it with mysql_fetch_assoc(), so here is what my original query is(not the one im having trouble with):
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC
what this does is selects the last 3 comments on a post, then orders them in another way (so they show up in the correct order, old to new) Now this is the query for echoing out the array of comments directly.
But now what I want to do, is to just get the first id out of the 3 comments.
here's what I have tried to do (and by the way, this query DOES work, when i replace my previous query to echo out the results in an array, but i need to get just the id for use, i don't want an array):
$previousIDq = mysql_fetch_assoc(mysql_query("
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1"));
$previousID = $previousIDq['id']; //this doesn't return the id as I want it to.
Your problem may be that there are no matching rows.
Also, I think you could also improve your query to this:
SELECT * FROM comments WHERE postID='$id' AND state='0' ORDER BY id DESC LIMIT 2,1
But as others say, use PDO or MySQLi, and with prepared statements. And don't SELECT * ever.
try a var_dump($previousID) to see what you get
It is probably giving you back an object, and you need to get your id from that object
You script is too condensened for error handling, let alone debugging
$mysql = mysql_connect(...
$query = "
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1
";
$result = mysql_query($query, $mysql);
if ( !$result ) { // query failed
die('<pre>'.htmlspecialchars(mysql_error($mysql)).'</pre><pre>'.htmlspecialchars($query).'</pre>');
}
$previousIDq = mysql_fetch_assoc($result);
if ( !$previousIDq ) {
die('empty result set');
}
else {
$previousID = $previousIDq['id'];
}
You need to separate your code to be able to debug
$query = "SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1";
$result = mysql_query($query);
echo mysql_error(); //what eror comes out here
while($previousIDq = mysql_fetch_assoc($result))
{
print ($previousIDq['id']);
}
NOTE: mysql_* is depreciated, upgrade to mysqli or PDO
Please stop using mysql_ functions to write new code, it is being deprecated. Use mysqli_ or PDO functions (mysqli below).
Bind your parameters to prevent SQL injection
Always use a column list (don't use SELECT *)
If you're returning > 1 row, use a while loop
mysqli_ solution
$link = mysqli_connect("localhost", "user_name", "password", "stock");
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$stmt = mysqli_prepare($link, "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = ? AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC");
mysqli_bind_param($stmt, 's', $id) or die(mysqli_error($dbh));
$result = mysqli_stmt_execute($stmt) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result)) {
echo $row[id];
}
mysqli_close($link);
mysql_ solution
$stmt = "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = $id AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC";
$result = mysql_query($stmt) or die(mysql_error());
$row = mysql_fetch_assoc($result);
while($row = mysql_fetch_assoc($result)) {
echo $row[id];
}

select row where the slot is the biggest

i need to select one row where slot_left is the biggest. i tried
for ( $i=1;$i<3;$i++) {
$sql5 = "SELECT * from user u where (
select max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$name'
)";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
// echo the id which the slot_left is the biggest
echo $i['slot_left'];
}
}
but still cannot. please help!
You have to use GROUP BY in your query.
And query execution in Loop is not recommended, it will decrees performance.
Try this.
$sql5 = "select c.id, max(slot_left) from company c,user u
where c.id=u.company_id and c.id='$id' GROUP by c.id";
$result5 = mysqli_query($link, $sql5) or die(mysqli_error($link));
while($row=mysqli_fetch_array($result5)) {
echo $row['slot_left'];
}
SQL can be. You select all rows from DB.
$sql5 = "select max(slot_left) AS slot_left from company c,user u where c.id=u.company_id and c.id='$name' GROUP by u.company_id";
$name variable used in query not set
Variable $i is not array. Array is $row
echo $row['slot_left'];

Categories