retrieve data by inner join with defined variable in Codeigniter - mysql

I want to get the following result of the mysql code by codeignitor.
It gives non equals id's(tbl_user) for the provided time frame in tbl_user_unavailability table
MySql code
SELECT tbl_user.id
FROM tbl_user
INNER JOIN tbl_user_unavailability
on tbl_user_unavailability.user_id <> tbl_user.id
WHERE '2018-02-02' BETWEEN begin_date AND end_date;
Result
22
25
find the mysql code result screenshot here
to get this result by codeignitor ,I have used following codes
Controller code
public function test(){
$current_date = '2018-02-02';
$available_users = $this->mod_users->test_test($current_date);
$data['available_users'] = $available_users;
//to test the result array
//var_dump($available_users);die();
$data['related_view']='user_unavailable_new';
$this->load->view('template', $data);
}
Model code
public function test_test($current_date){
$this->load->database();
$this->db->select('*');
$this->db->join('tbl_user_unavailability', 'tbl_user_unavailability.user_id <> tbl_user.id','inner');
$this->db->where("'$current_date' BETWEEN 'tbl_user_unavailability.begin_date' AND 'tbl_user_unavailability.end_date'");
$query = $this->db->get($this->table);
return $query->result_array();
}
Result
not showing anything
I have tested it with var_dump($available_users);die();
It shows empty array

Related

How to convert this query to doctrine DQL

SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
select 1
from `distribution_mobiletokens`
where userid = '20'
and deviceid = dm.deviceid
and created > dm.created
)
What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.
My database looks like below.
For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))
Things I've Tried
$mobiletokens = $em->createQueryBuilder()
->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
->from('AppBundle:MobileTokens', 'u')
->leftJoin('u.companyId', 'company')
->leftJoin('u.userId', 'user')
->where('u.status = 1 and user.id = :userid')
->setParameter('userid',(int)$jsondata['userid'])
->groupby('u.apntoken')
->getQuery()
->getResult();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}
die();
This gives me the incorrect response of
63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
Any help here is appreciated!
Other Information
Data with SELECT * FROM
Data after using the SQL I provided up top.
You could use a subselect created with the querybuilder as example:
public function selectNewAppToken($userId)
{
// get an ExpressionBuilder instance, so that you
$expr = $this->_em->getExpressionBuilder();
// create a subquery in order to take all address records for a specified user id
$sub = $this->_em->createQueryBuilder()
->select('a')
->from('AppBundle:MobileTokens', 'a')
->where('a.user = dm.id')
->andWhere('a.deviceid = dm.deviceid')
->andWhere($expr->gte('a.created','dm.created'));
$qb = $this->_em->createQueryBuilder()
->select('dm')
->from('AppBundle:MobileTokens', 'dm')
->where($expr->not($expr->exists($sub->getDQL())))
->andWhere('dm.user = :user_id')
->setParameter('user_id', $userId);
return $qb->getQuery()->getResult();
}
I did this for now as a temporary fix, not sure if this is best answer though.
$em = $this->em;
$connection = $em->getConnection();
$statement = $connection->prepare("
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid=:userid
and not exists (
select 1
from `distribution_mobiletokens`
where userid = :userid
and deviceid = dm.deviceid
and created > dm.created
)");
$statement->bindValue('userid', $jsondata['userid']);
$statement->execute();
$mobiletokens = $statement->fetchAll();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}

Codeigniter | Calling Stored Procedure with IN and OUT pratameters in MYSQL

This is my procedure... it's going to accept a parameter of $encoder as IN and then it will output the number of members as #current, #cancelled and #year it was encoded as OUT. I got one IN parameter ans four OUT parameters... and it works.
The problem is how am i going to do this in Codeigniter 3.
I've tried several codes refering to the codeigniter manual but i got this error..
Error Number: 1172
Result consisted of more than one row
CALL get_members_by_status(25,#current,#current,#year1)
Filename: models/Dashboardcounts.php
Line Number: 189
This is the Mysql Procedure code..
BEGIN
-- current members
SELECT
count(memstat) INTO current
FROM
members
WHERE
encoder = encoder_num
AND memstat = '1';
-- canceled members
SELECT
count(memstat) INTO cancelled
FROM
members
WHERE
encoder = encoder_num
AND memstat = '0';
-- year encoded
SELECT
date_format(memdateencode,"%Y") INTO year1
FROM
members
WHERE
encoder = encoder_num;
END
This is my Model Code...
public function linegraphchurchmemberbychurch_2(){
$query = $this->db->query('CALL get_members_by_status(25,#current,#current,#year1)');
$query1 = $this->db->query('SELECT #current');
foreach ($query1->result_array() as $row){
$data = $row;
}
return $data;
}
Any hint?

Mysql PDO (Getting total from all colums) [duplicate]

I'm new to php and I've searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I'm trying to pick one column from the whole table and add them all together. Here is what I got. All this tells me is how many rows there are that match my query, not the total sum of column I want. Any help is appreciated.
$res1 = $db->prepare('SELECT sum(distance) FROM trip_logs WHERE user_id = '. $user_id .' AND status = "2"');
$res1->execute();
$sum_miles = 0;
while($row1 = $res1->fetch(PDO::FETCH_ASSOC)) {
$sum_miles += $row1['distance'];
}
echo $sum_miles;
You're only returning one row in this instance. Modify your summed column to have an alias:
SELECT SUM(distance) AS totDistance FROM trip_logs ....
Now you can can fetch the row -
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['totDistance'];
No need to loop.
You can use SUM() without explicitely grouping your rows because if you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.
If however you want to use the SUM() function for something slightly more complicated you have to group your rows so that the sum can operate on what you want.
If you want to get multiple sums in a single statement, for example to get the distance for all users at once, you need to group the rows explicitely:
$res1 = $db->prepare("
SELECT
SUM(distance) AS distance,
user_id
FROM trip_logs WHERE status = '2'
GROUP BY user_id
");
$res1->execute();
while ($row = $res1->fetch(PDO::FETCH_ASSOC))
{
echo "user $row[user_id] has runned $row[distance] km.\n";
}
This will return the sum of distances by user, not for all users at once.
Try this if you are using a Class :
class Sample_class{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function GetDistant($user_id,$status) {
$query = $this->db->prepare("SELECT sum(distance) FROM trip_logs WHERE user_id =? AND status =?");
$query->bindValue(1, $user_id);
$query->bindValue(2, $status);
try{ $query->execute();
$rows = $query->fetch();
return $rows[0];
} catch (PDOException $e){die($e->getMessage());}
}
}
$dist = new Sample_class($db);
$user_id = 10;
$status = 2;
echo $dist->GetDistant($user_id,$status);

Eloquent: Nested query to revert order in limited result

The following function (in my User Model) gives me the correct result for my chat system. Almost... I need to revert the order of the results.
public function getChatConv($cp, $page=1){
$limit = $page * 20;
$user = Authek::curUser();
$res = Chatmessage::where('receipient',$cp)->where('sender',$user->id)
->orWhere('receipient',$user->id)->where('sender',$cp)
->orderBy('created_at','desc')->take($limit)->get();
return $res;
}
It returns an object and I need an object as result. I tried already to convert the result to an array, revert the order and then convert the array back to object. This didn't work.
What I need is a nested query like the following raw SQL query:
SELECT *
FROM (
SELECT *
FROM chatmessages
WHERE (
receipient = '422'
AND sender = '22'
)
OR (
receipient = '22'
AND sender = '422'
)
ORDER BY created_at DESC
LIMIT 0 , 20
)faketable
ORDER BY created_at ASC
There are a few articles with nested queries, but I don't find a similar case and it would be good if someone could do this in Eloquent without the use of Raw queries... It must be possible.
Try this..
use take() and skip(),offset()
get 4 items from offset 3/4th:
Chatmessage::take(4)->offset(3)->get();
Or this (get 10 items from 8rd row):
Chatmessage::take(10)->skip(2)->get();
public function getChatConv($cp, $page=1){
$limit = $page * 20;
$user = Authek::curUser();
$res = Chatmessage::where('receipient',$cp)->where('sender',$user->id)
->orWhere('receipient',$user->id)->where('sender',$cp)
->orderBy('created_at','desc')->take(3)->skip(2)->get();
return $res;
}

Mysql count rows function

I have created a simple function which takes user id and show total no. of post by the user id
function totalpost($user_id){
$sql = 'SELECT * FROM posts WHERE u_id='.$user_id;
$total = mysql_num_rows(mysql_query($sql)) or die(mysql_errno());
return $total;
}
Its working fine, but when 0 record found, it not returns anything.
I want to return 0 if there are no record found
Please help
function totalpost($user_id){
$sql = 'SELECT count(*) FROM posts WHERE u_id='.intval($user_id);
$res = mysql_query($sql)) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_row($res);
return $row[0];
}
not because you need 0, but because you have to always use count() instead of selectiong all users posts which can be big load of data.
Try this query:
SELECT COUNT(*) FROM posts WHERE u_id=xx
By using the COUNT function you will guarantee a 0 will be returned even if no rows match the WHERE clause.