Order MySQL inbox by newest conversation first? - php

I've a MySQL/PHP code for a private messaging system that I built. It works great although I'm fairly new to it all so struggling to get the message threads to display by newest first. Is there any chance you could offer advice? The current code is as follows:
$result = '';
$nowTime = time();
$getmessages = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' GROUP BY msg_from ORDER BY ID DESC");
while($iamessages = mysql_fetch_array($getmessages))
{
$msg_id = $iamessages['ID'];
$msg_from = $iamessages['msg_from'];
$msg_conversation = $iamessages['conversation'];
$getmsgdata = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' AND msg_from = '$msg_from' ORDER BY ID DESC LIMIT 1");
while($imsd = mysql_fetch_array($getmsgdata))
{
$msg_message = $imsd['msg_message'];
$msg_time = $imsd['time'];
$msg_read = $imsd['msg_read'];
}
$msg_conversation = suitcrypt($msg_conversation);
if ( $msg_read == 'no' ) { $msgclass = "messagepostunread"; } else { $msgclass = "messagepost"; }
$getfromdata = mysql_query("SELECT FullName, Username, status FROM members WHERE ID = '$msg_from'");
while($ifd = mysql_fetch_array($getfromdata))
{
$msg_from_name = $ifd['FullName'];
$msg_from_username = $ifd['Username'];
$msg_from_status = $ifd['status'];
}
$getfromdata1 = mysql_query("SELECT Link FROM images WHERE MemberID = '$msg_from' AND is_primary = 'yes'");
while($ifd1 = mysql_fetch_array($getfromdata1)) {
$msg_from_img = $ifd1['Link'];
}
$timepass = timing($msg_time);
if ( $timepass == 'data' ) {
$timepass = date("dS M", $msg_time);
}
if ( ( $msg_from_status == 'full' ) || ( $msg_from_status == 'active' ) ) {
$result .= "
<div class=\"$msgclass\" onclick=\"showconversation('$msg_conversation');\">
<img src=\"m/members_image/$msg_from/thumb-$msg_from_img\" class=\"feedpic\" width=\"55\" height=\"55\" /><div class=\"messageposttext\">$msg_from_name:<div class=\"inboxfeedreply\">Reply ยท $timepass</div><br />$msg_message</div>
</div>
<div class=\"splittermessages\"></div>
";
}
Within each table entry in the messages table there is a 'time' stamp. Here's an example of the time entries: 1367680391. What's the best way to order the threads by newest reply first?

First off I think you should group by $msg_conversation and find the last date on each conversation. With the code below you have the conversatons ordered by the last message each conversation/thread had.
$result = '';
$nowTime = time();
$getmessages = mysql_query("SELECT conversation, max(date) FROM messages WHERE msg_to = '$session_memberid' GROUP BY conversation ORDER BY max(date)");
while($iamessages = mysql_fetch_array($getmessages))
{
$msg_conversation = $iamessages['conversation'];
...
Further on you can get the messages for each conversation by date descending.

I got someone to help and the answer was to update the query to the following:
$getmessages = mysql_query("SELECT * FROM messages WHERE msg_to = '$session_memberid' GROUP BY msg_from ORDER BY MAX(time) DESC");

Related

MYSQL NOT IN Query not working unless hard coded

I'm fairly new to Javascript and PHP so I have no idea what I'm doing for the most part. I'm trying to make a Room Booking System.
$booking_id = '';
if(isset($_POST['edit_button_booking'])){
$booking_id = $_POST['edit_id'];
}
echo "<script>alert('$booking_id')</script>";
$today_date = date('Y-m-d');
$room_query = "SELECT * FROM rooms";
$room_run = $conn->query($room_query);
if($room_run->num_rows>0){
$options = mysqli_fetch_all($room_run, MYSQLI_ASSOC);
}
$start_from = 8;
$end_from = 21;
$start_to = $start_from+1;
$end_to = $end_from+1;
$from_booked = [];
$to_booked = [];
if(isset($_POST['value'])){
$room_id = $_POST['value'];
$specify_query = "SELECT * FROM rooms WHERE room_id = '$room_id'";
$specify_run = $conn->query($specify_query);
$row = mysqli_fetch_assoc($specify_run);
$room_name = $row['room_name'];
$disable_query = "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '$today_date' AND room_id = '$room_id' AND booking_id NOT IN (SELECT booking_id FROM booking WHERE booking_id = '$booking_id')";
$disable = $conn->query($disable_query);
if($disable->num_rows > 0){
while($row = $disable->fetch_assoc()){
$from_booked_hour = date_parse($row['booking_start'])['hour'];
$to_booked_hour = date_parse($row['booking_end'])['hour'];
$from_booked = array_merge($from_booked, range($from_booked_hour, $to_booked_hour-1));
$to_booked = array_merge($to_booked, range($from_booked_hour+1, $to_booked_hour));
}
}
}
This is my code. What this code is supposed to do is to display the booked time slots for the room except for the chosen time slot.
And yet, it keeps on displaying both booked times when I want the 9 -12 time slot to be omitted from the time table
The alert that I used show that $booking_id has the value '000053' which is the id of the booking that I want not shown in the time table.
If I were to hard code it to $booking_id = '000053' or $booking_id = 53, it works.
$booking_id = '';
if(isset($_POST['edit_button_booking'])){
$booking_id = $_POST['edit_id'];
}
$booking_id = 53;
echo "<script>alert('$booking_id')</script>";
$today_date = date('Y-m-d');
$room_query = "SELECT * FROM rooms";
$room_run = $conn->query($room_query);
if($room_run->num_rows>0){
$options = mysqli_fetch_all($room_run, MYSQLI_ASSOC);
}
$start_from = 8;
$end_from = 21;
$start_to = $start_from+1;
$end_to = $end_from+1;
$from_booked = [];
$to_booked = [];
if(isset($_POST['value'])){
$room_id = $_POST['value'];
$specify_query = "SELECT * FROM rooms WHERE room_id = '$room_id'";
$specify_run = $conn->query($specify_query);
$row = mysqli_fetch_assoc($specify_run);
$room_name = $row['room_name'];
$disable_query = "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '$today_date' AND room_id = '$room_id' AND booking_id NOT IN (SELECT booking_id FROM booking WHERE booking_id = '$booking_id')";
$disable = $conn->query($disable_query);
if($disable->num_rows > 0){
while($row = $disable->fetch_assoc()){
$from_booked_hour = date_parse($row['booking_start'])['hour'];
$to_booked_hour = date_parse($row['booking_end'])['hour'];
$from_booked = array_merge($from_booked, range($from_booked_hour, $to_booked_hour-1));
$to_booked = array_merge($to_booked, range($from_booked_hour+1, $to_booked_hour));
}
}
}
I don't know what is causing this issue. Any help will be appreciated.
The var_dump of both queries are as follows:
Generated SQL:
string(156) "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '2022-07-22' AND room_id = '1' AND booking_id != '53'"
Hard Coded:
string(156) "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '2022-07-22' AND room_id = '1' AND booking_id != '53'"
UPDATE:
The var_dump()'s I posted earlier were outside of the if(isset($_POST['value'])) block since I thought the variable $booking_id can be accessed in the if block as well. I tried to use var_dump() inside the if block and it turned out that the $booking_id was turning up blank.
string(154) "SELECT booking_id, room_id, booking_date, booking_start, booking_end FROM booking WHERE booking_date = '2022-07-22' AND room_id = '1' AND booking_id != ''"
This was the result of the var_dump() running inside of the if block. I don't understand why it is doing this though. My $today_date variable was defined outside of the if block as well and that's working.

php mysql query is not doing sum properly

I am doing sum with the below query but it is not giving result properly.
If there are four items and it is showing the result like:
1.000 2.000 3.000 4.000 and it should be like 10.000
I don't know where I am mistaken please help.
<?php
$order_temp = mysql_query("select * from temp_cart
where item_id = '".$mitem_idC."' and ses_mem=113 order by id");
while ($torder = mysql_fetch_array($order_temp)) {
$prITTC = $torder['item_id'];
$qtyT = $torder['qty'];
$chTP = mysql_query("
select * from temp_choices
where item_id = '".$prITTC."'
AND ses_mem = 113
AND status = 1
");
while($chGET = mysql_fetch_array($chTP)){
$fID = $chGET['id'];
$field = $chGET['choice_id'];
$order_tempCHP = mysql_query("
select sum(price) as total, id, ename, choice_id, item_id, price
from choice_price
WHERE
id IN('$field')
");
while ($torderCP = mysql_fetch_assoc($order_tempCHP)){
$totalCH = $torderCP['total'];
$tsl = $totalCH+($qtyT*$prIDTC);
$altsl = number_format($tsl, 3, '.', '');
echo $altsl;
} }
}
?>
according to my question above after trying and trying i found the solution and resolved my problem according to below code:
Thanks to #John Kugelman at MySQL query using an array
$order_temp = mysql_query("select * from temp_cart
where item_id = '".$mitem_idC."' and ses_mem=113 order by id");
while ($torder = mysql_fetch_array($order_temp)) {
$prITTD = $torder['id'];
$prITTC = $torder['item_id'];
$chTPaa = mysql_query("
select choice_id
FROM temp_choices
WHERE item_id = '$prITTC'
AND ses_mem = 113
AND status = 1
group by choice_id
");
while ($chGETaa = mysql_fetch_assoc($chTPaa)){
$temp[] = $chGETaa['choice_id'];
}
$thelist = implode(",",$temp);
$order_tempCHP = mysql_query("
select sum(price) as total
from choice_price
WHERE
id IN ($thelist)
AND
item_id = '".$prITTC."'
");
while($torderCP = mysql_fetch_assoc($order_tempCHP)){
$totalCH = $torderCP['total'];
$tsl = $totalCH+($qtyT*$prIDTC);
$altsl = number_format($tsl, 3, '.', '');
echo $altsl;
} }

Choosing the correct SQL query based off user input

Lets say the user only entered in an artist to search by, how do I get PHP to recognize that the user is only looking for an artist and should therefore setup a query only for the artist. The way I have currently done it works, but it is very ineffective when the user wants a variety of search options.
$artist = $_POST["artistSearch"];
$topic= $_POST["topicSearch"];
$date = $_POST["dateSearch"];
$title = $_POST["titleSearch"];
$artistLength = strlen($artist);
$topicLength = strlen($topic);
$dateLength = strlen($date);
$titleLength = strlen($title);
if ($artistLength>2 && $topicLength<2 && $dateLength<2 && $titleLength<2) {
$sql=("Select * FROM music WHERE artist = '$artist' ORDER BY date");
}
if ($artistLength>2 && $topicLength>2 && $dateLength<2 && $titleLength<2) {
$sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' ORDER BY date");
}
if ($artistLength>2 && $topicLength>2 && $dateLength>2 && $titleLength<2) {
$sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' AND date = '$date' ORDER BY date");
}
if ($artistLength>2 && $topicLength>2 && $dateLength>2 && $titleLength>2) {
$sql=("Select * FROM music WHERE artist = '$artist' AND topic = '$topic' AND date = '$date' AND title = '$title' ORDER BY date");
}
$result = mysqli_query($con,$sql);
Simple, you build up the query string in stages. Ignoring your sql injection attack vulnerability, and assuming that all options should be ANDed together, you can do something like:
$options = array();
if ($artist) {
$options[] = "artist = '$artist'";
}
if ($topic) {
$options[] = "topic = '$topic'";
}
etc...
$where_clause = implode(' AND ', $options);
$sql = "SELECT ... WHERE $where_clause";

mysql_query returning wrong result

Consider the following code
if ( isset( $_SESSION['FBID'] ) ) {
$uid = $_SESSION['FBID'];
$sql = "SELECT *, count(member_nr) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
$notification = $row['notifyMe'];
}//while
if ( $notification > 0 ) {
echo '<span class="badge">' . $notification . '</span>';
} //if
var_dump($notification);
} //isset( $_SESSION['FBID'] )
The above script returns how many notifications a member has as you can see in image below
My Problem
The script is returning the wrong result (wrong number of notifications). Have a look at the table below, the member number appears 3 times in the table so:
$notification = $row['notifyMe'] Should = 3 AND NOT 1
What am I missing or doing wrong here? Thanks for reading
Use
$sql = "SELECT *, count(*) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
Notice count(*) , it will fetch how many records are matching criteria.
And initialize $notification = 0; at the start.
Have you tried approaching it from this angle
$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = array();
while($row=mysql_fetch_array($result)){
$notification[] = $row['notifyMe'];
}
//an array count on notification should give you the number of elements in the array i.e those that matched the query
$total_count = count($notification);
In your code the notification will be always one, since it will take only the notifyMe field of last row in the result set.
If you want to get number of notifications, try this
if ( isset( $_SESSION['FBID'] ) ) {
$uid = $_SESSION['FBID'];
$sql = "SELECT *, count(member_nr) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = 0;
while($row=mysql_fetch_array($result)){
$notification++;
/*
OR $notification += $row['notifyMe'];
*/
}//while
if ( $notification > 0 ) {
echo '<span class="badge">' . $notification . '</span>';
} //if
var_dump($notification);
} //isset( $_SESSION['FBID'] )
$sql = "SELECT *
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = mysql_num_rows($result);
$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
echo "Toal notification".mysqli_num_rows($result);
}
mysqli_close($con);
?>

Using multiple while loops getting only 1 record

I am just starting to learn php, so bear with me...
I am trying to get a list of employees from a list of supervisors.
I am only getting the last supervisor ..
I am guessing that it is because I have the code in the wrong places..
Here is the code I have so far..
//Get List of Supervisors
$result_supervisors = mysql_query("SELECT emp_no as semp_no, full_name as sfull_name,employee_email as s_email FROM employees where supervisor = '1' ORDER BY emp_no");
// Initializes Supervisor Array
$supervisors = array();
while($row = mysql_fetch_array($result_supervisors, MYSQL_ASSOC))
{
$supervisor = $row['semp_no'];
$supervisor_name = $row['sfull_name'];
$supervisor_email = $row['s_email'];
//add row to supervisors array
$supervisors[] = array($supervisor, $supervisor_name, $supervisor_email);
}
//Get employee for the supervisor
$empquery = "SELECT emp_no, full_name, review_date,employee_email as e_email FROM employees where review_date < curdate() and employment_status !='2' and emp_supervisor = ". $supervisor ;
$empresult = mysql_query($empquery);
while($emprow = mysql_fetch_array($empresult))
{
if ($emprow['cnt'] == '0')
{
// no records for supervisor
}
else
{
$emp_no = $emprow['emp_no'];
$full_name = $emprow['full_name'];
$e_email = $emprow['e_email'];
$review_date = $emprow['review_date'];
//add row to employees array
$employees[] = array($supervisor, $supervisor_name, $supervisor_email,$emp_no,$full_name,$e_email,$review_date);
}
}
print_r($employees);
I am trying to put the results into an html table and email it to the supervisor for the end result..
But getting more than one supervisor is my biggest issue..
Is there an easy way to put the data into an html table.. in case someone knows why only one supervisor is being done...
Any help that can help a newbie?
KD
Change your first query:
$result_supervisors = mysql_query("SELECT emp_no as semp_no, full_name as sfull_name,employee_email as s_email FROM employees ORDER BY emp_no");
Try this code :
//Get List of Supervisors
$result_supervisors = mysql_query("SELECT emp_no as semp_no, full_name as sfull_name,employee_email as s_email FROM employees where supervisor = '1' ORDER BY emp_no");
// Initializes Supervisor Array
$supervisors = array();
$employees = array();
while($row = mysql_fetch_array($result_supervisors, MYSQL_ASSOC))
{
$supervisor = $row['semp_no'];
$supervisor_name = $row['sfull_name'];
$supervisor_email = $row['s_email'];
//add row to supervisors array
$supervisors[] = array($supervisor, $supervisor_name, $supervisor_email);
//Get employee for the supervisor
$empquery = "SELECT emp_no, full_name, review_date,employee_email as e_email FROM employees where review_date < curdate() and employment_status !='2' and emp_supervisor = ". $supervisor ;
$empresult = mysql_query($empquery);
while($emprow = mysql_fetch_array($empresult))
{
if ($emprow['cnt'] == '0')
{
// no records for supervisor
}
else
{
$emp_no = $emprow['emp_no'];
$full_name = $emprow['full_name'];
$e_email = $emprow['e_email'];
$review_date = $emprow['review_date'];
//add row to employees array
$employees[] = array($supervisor, $supervisor_name, $supervisor_email,$emp_no,$full_name,$e_email,$review_date);
}
}
}
print_r($employees);

Categories