I would like to order the results of my MySQL query by their DateTime value which is under column 'timestamp' for each one.
I tried adding
$reactions = DB::query('SELECT * FROM reactions WHERE poster_id=:userid', array(':userid' => $userid));
$comments = DB::query('SELECT * FROM comments WHERE poster_id=:userid', array(':userid' => $userid));
$mentions = DB::query('SELECT * FROM comments WHERE FIND_IN_SET(:users , users)', array(':users' => $userid));
$postMentions = DB::query('SELECT * FROM posts WHERE FIND_IN_SET(:users , users)', array(':users' => $userid));
$likedMessages = DB::query('SELECT * FROM messages WHERE sender_id:senderid AND liked=:liked', array(':senderid' => $userid, ':liked' => 1));
$reports = DB::query('SELECT * FROM reports WHERE user_id=:userid AND status=:status OR status=:status2', array(':user_id' => $userid, ':status' => 1, ':status2' => 2));
But this doesn't order them at all.
Edit:
To be more clear; I would like to combine all the results from the queries then order those by timestamp
Use order by at the end of your query
ORDER BY `timestamp` DESC
Related
I have written in one SQL query and it's working fine. How do I write this in codeigniter?
$sql = "SELECT *
FROM single_message
WHERE
( school_id='$schoolId' AND
classId='$classId' AND
sectionId='$sectionId' AND
sender_id='$senderId' AND
receiver_id ='$receiverId'
) OR
( chool_id='$schoolId' AND
classId='$classId' AND
sectionId='$sectionId' AND
sender_id='$receiverId' AND
receiver_id ='$senderId'
)
ORDER BY messageId DESC"`;
This is what I've tried:
$condition = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $senderId,
'receiver_id' => $receiverId
);
$this->db->select('*');
$this->db->where($condition);
return $this->db->get('single_message')->result_array();
As per your SQL query:
$sql = "SELECT * FROM single_message WHERE (school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId') ORDER BY messageId DESC";
There are two ways to write queries. I will explain both way one by one:
Solution 1st:
You can simply just put your condition in where clause like explained below->
$condition = "(school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId')";
$this->db->select('*');
$this->db->where($condition);
return $this->db->get('single_message')->result_array();
Here you can see that I have passes complete where condition in a string format. This is the fisrt solution. Another method to write this query is.
Solution 2nd:
Query grouping-> It allows you to create groups of WHERE clauses by enclosing them in parentheses. So query would be like:
$condition['AND'] = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $senderId,
'receiver_id' => $receiverId
);
$condition['OR'] = array(
'school_id' => $schoolId,
'classId' => $classId,
'sectionId' => $sectionId,
'sender_id' => $receiverId,
'receiver_id' => $senderId
);
$this->db->select('*');
// Starts first group
$this->db->group_start();
// AND condition placed in below line
$this->db->where($condition['AND']);
// First group ends here
$this->db->group_end();
// Another group has been started here for OR clause
$this->db->or_group_start();
// Here we placed our OR codition
$this->db->where($condition['OR']);
// Second group ends here
$this->db->group_end();
return $this->db->get('single_message')->result_array();
It will produce exact result you needed. Let me know if you have any query. For more details you can read Query Builder explaination here: Query Grouping
Passing second parameters as null and third parameter as false will result is not escaping your query.
Try this code:
$this->db->select('*');
$this->db->where("school_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$senderId' AND receiver_id ='$receiverId') OR (chool_id='$schoolId' AND classId='$classId' AND sectionId='$sectionId' AND sender_id='$receiverId' AND receiver_id ='$senderId'", null, false);
$this->db->order_by("messageId", "desc");
$this->db->get();
Here is Where reference from codeigniter documentation.
This is my query:
SELECT * FROM mytable WHERE `USER` = '1599' AND `id` = '124253' AND `wednesday` IS NULL
This is the php code:
$check = Test::model()->find("id =:id and user =:user and ".$day." =:day ", array(":id" => $check_lunch_per_day, ":user" => $user, 'day'=> null));
another try:
$check = Test::model()->find("id =:id and user =:user and ".$day." =:day ", array(":id" => $check_lunch_per_day, ":user" => $user, 'day'=> 'IS NULL'));
But the result of the check is always null. What should I do? I want to get the wednesday column value if it is null.
This should work,
setting :day to IS NULL
$check = Test::model()->find("id =:id and user =:user and ".$day." =:day ",
array(":id" => $check_lunch_per_day, ":user" => $user, ':day'=> 'IS NULL'));
When i try to run this with php/pdo the result is empty, but when i replace the variables and echo the query and copy paste to phpmyadmin it works as it should.
I guess that it have something to do with the BETWEEN part in the query, it works if I remove it.
php code:
$sql = 'SELECT * from `activity`
WHERE `activity`.`employee_id` = :id
AND `activity_endtime` BETWEEN :start
AND :end
ORDER BY :order LIMIT 0 ,:limit';
$date_end = date('Y-m-d',time());
$date_start = date('Y-m-01',strtotime($date_end));
$values = array(
':id' => $_SESSION['user_id'],
':start' => '"'.$date_start.'"',
':end' => '"'.$date_end.'"',
':order' => 'activity_id',
':limit' => '10');
$q->execute($values);
while($r = $q->fetch(PDO::FETCH_ASSOC)){
//does not get here after adding the between part
}
The query that i get from replacing the parameters and echoing:
SELECT * from `activity`
WHERE `activity`.`employee_id` = 7
AND `activity_endtime` BETWEEN "2014-08-01"
AND "2014-08-18"
ORDER BY activity_id LIMIT 0 ,10
Don't wrap the values with quotes.
Change
':start' => '"'.$date_start.'"',
':end' => '"'.$date_end.'"',
to
':start' => $date_start,
':end' => $date_end,
and let me know if it worked for you.
What I'm trying to do is search through my table and count the instances of a letter, and store the ID of each instance in mysql and php (PDO).
What I had been messing around with is this:
$user = 'john';
$stmt = $pdo->prepare("SELECT id, SUBSTR(surname, 1, 1) as surname_init,COUNT(*) as count FROM first_table WHERE user = :user GROUP BY surname_init ORDER BY count DESC");
$stmt->bindValue(":user", $user);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($row);
This is the result:
array (size=2)
0 =>
array (size=3)
'id' => string '3' (length=1)
'surname_init' => string 'B' (length=1)
'count' => string '2' (length=1)
1 =>
array (size=3)
'id' => string '7' (length=1)
'surname_init' => string 'D' (length=1)
'count' => string '1' (length=1)
So I have two results: B has 2 instances, D has one. However "B" has only one resulting id returned from two.
Is this possible? I think I'm missing something here..
Use GROUP_CONCAT() to get all rows that matched the group by, like:
SELECT
GROUP_CONCAT(id) AS id_list,
SUBSTR(surname, 1, 1) as surname_init,
COUNT(*) as count
FROM first_table
WHERE user = :user
GROUP BY surname_init
ORDER BY count DESC
See if this helps:
$user = 'john';
// use this to get unique starting characters for surnames for the user John
$stmt = $pdo->prepare("SELECT SUBSTR(surname, 1, 1) as `surname_init`,
COUNT(*) as `count` FROM first_table
WHERE user = :user GROUP BY
surname_init ORDER BY count DESC");
$stmt->bindValue(":user", $user);
$stmt->execute();
$rows1 = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows1 as $row1){
echo "<BR>Starting Letter: " . $row1['surname_init'];
echo "<BR>Count: " . $row1['count'];
// now get all the IDs for this user that have the
// surnames starting with this alphabet
$stmt = $pdo->prepare("SELECT ID, SUBSTR(surname, 1, 1) as `surname_init`,
FROM first_table
WHERE user = :user
AND surname LIKE :surname");
$stmt->bindValue(":user", $user);
$stmt->bindValue(":surname", $row1['surname_init']."%");
$stmt->execute();
$rows2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows2 as $row2){
// do insert based on ID here
}
}
I'm trying to use Group by in find method for my relational database I want to get the latest record with unique receiver_id out of result set filtered by user_id and below is my code:
$this->loadModel('Chat');
$lastChat = $this->Chat->find('all', array(
'conditions' => array(
'Chat.user_id' => $user_id['User']['id']
),
'fields' => array(
'Chat.id',
'Chat.chat',
'Chat.user_id',
'Chat.receiver_id',
'Chat.read',
'Chat.created'
),
'group' => array('Chat.receiver_id'),
'order' => array('Chat.created DESC')
));
However, this does not seem to work. I'm not sure why but I'm only getting one result...
How can I get multiple results with rules based on above.
Try the following:
$db = $this->Chat->getDataSource();
$chats = $db->query("SELECT * , (Chat.user_id + Chat.receiver_id) AS dist
FROM (
SELECT *
FROM chats t
WHERE ( t.user_id =$id OR t.receiver_id =$id )
ORDER BY t.id DESC
) Chat
GROUP BY dist
ORDER BY Chat.id DESC");