this is my query working fine
$offset = ($this->uri->segment(4))?$this->uri->segment(4):0;
$limit =10;
i donn't use $user_id becoz this function uses pagination
$q = "select distinct attandence.user_id ,monthname(date), sum(is_absent) as absents,in_time,out_time , count(date) as working_days, leave_type , users.f_name ,leave_types.type ,leave_types.leave_type_id , users.l_name ,( select count(leave_type) from attandence where leave_type != 0 and user_id = 4 and month(date) = 10 ) as leave_count from attandence join users on (users.user_id = attandence.user_id) left join leave_types on(leave_types.leave_type_id = attandence.leave_type) where in_time != '' and out_time != '' ".$where_condition." GROUP BY attandence.user_id LIMIT ".$limit." OFFSET ". $offset;
$rows = $this->attandence_model->q($q);
$this->data['Details'] = $rows;
in view i just passed
<? foreach ($Details as $detail){ ?>
<? } ?>
Any help is going to be appreciated. :)
I have solution your query you can add sub query Sub query
See Example:
$q = "select distinct attandence.user_id ,monthname(date), sum(is_absent) as absents,in_time,out_time , count(date) as working_days, leave_type , users.f_name ,leave_types.type ,leave_types.leave_type_id , users.l_name, (select count(leave_type) from attandence where leave_type != 0 and user_id = 15 and month(date) = 10) as leave_count from attandence join users on (users.user_id = attandence.user_id) left join leave_types on(leave_types.leave_type_id = attandence.leave_type) where in_time != '' and out_time != '' ".$where_condition." GROUP BY attandence.user_id LIMIT ".$limit." OFFSET ". $offset;
Related
For some reason my script takes too much time, that is why i had to add the ini_set('max_execution_time', 300); since 30 seconds being the default got me a fatal error.
I can't understand why this is happening, if i go directly into SSMS i get that query in 0 secs. what can be happening? i am running wamp with php 5.4.16 and the extension php_sqlsrv_54_ts
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
ini_set('max_execution_time', 300);
include "ChromePhp.php";
$sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'Cliente';
$order = isset($_POST['order']) ? strval($_POST['order']) : 'DESC';
include "includes/db_config.php";
$conn = sqlsrv_connect(SV_NAME, $connectionInfo) OR die("Unable to connect to the database");
$sql =
"SELECT * FROM
(Select
Id
,Cliente
,Contrato
,Anexo
,SO
,NombreFlota
,(SELECT count(*) FROM LiveTest LEFT JOIN Producto ON Producto.Id=LiveTest.Producto_Id WHERE Producto.Order_Id=Orders.Id) as Hechas
,((SELECT count(*) FROM Producto WHERE Order_Id=Orders.Id) - (SELECT count(*) FROM LiveTest LEFT JOIN Producto ON Producto.Id=LiveTest.Producto_Id WHERE Producto.Order_Id=Orders.Id and RMA is null )) as Pendientes
,(SELECT count(*) FROM Producto WHERE Order_Id=Orders.Id ) as Total
FROM
Orders
WHERE
Orders.FechaPick is not null) as A
WHERE Total - Pendientes >0
ORDER BY $sort $order";
ChromePHP::log($sql);
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = array();
$res = sqlsrv_query($conn, $sql, $params, $options);
while($row = sqlsrv_fetch_object($res))
{
array_push($result, $row);
}
ChromePHP::log($result);
echo json_encode($result);
?>
try to modify your query like this:
Note : you do 'where f0b.Order_Id=f1.Id' then your left ouer join is cancelled because you test a value (that's why i have replaced by inner join), if you want null value too, you must do it : 'where f0b.Order_Id=f1.Id or f0b.Order_Id is null'
Select
Id
,Cliente
,Contrato
,Anexo
,SO
,NombreFlota
,isnull(f3.NbProdLive, 0) as Hechas
,isnull(f2.NbProd, 0) - isnull(f3.NbProdLiveRMANull, 0) as Pendientes
,isnull(f2.NbProd, 0) as Total
FROM
Orders f1
outer apply
(
select count(*) NbProd from Producto f0
where f0.Order_Id=f1.Id
) f2
outer apply
(
select count(*) NbProdLive, sum(case when RMA is null then 1 else 0 end) NbProdLiveRMANull
from LiveTest f0 INNER JOIN Producto f0b ON f0b.Id=f0.Producto_Id
where f0b.Order_Id=f1.Id
) f3
WHERE f1.FechaPick is not null and (isnull(f2.NbProd, 0) - (isnull(f2.NbProd, 0) - isnull(f3.NbProdLiveRMANull, 0))) >0
ORDER BY $sort $order
I have 3 queries which I run which are nearly identical, the latter two have an AND condition.
Main query:
$mess = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ?
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess->bind_param("i", $room);
$mess->execute();
$mess->store_result();
$mess->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row = $mess->fetch()){
//im fetching here in my <div class='div1' >
}
Then, in the second div I have to add an AND condition:
$mess2 = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ? AND voteup - votedown >= 5
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess2->bind_param("i", $room);
$mess2->execute();
$mess2->store_result();
$mess2->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row2 = $mess2->fetch()){
//im fetching here in my <div class='div2' >
}
Lastly, in the third div I have a slightly different AND condition:
$mess3 = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ? AND votedown - voteup >= 5
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess3->bind_param("i", $room);
$mess3->execute();
$mess3->store_result();
$mess3->bind_result($chatid,$chat_userid,$message,$voteup,$votedown,$date);
while($row3 = $mess3->fetch()){
//im fetching here in my <div class='div3' >
}
Everything works BUT doing this near-same query seems clumsy. Is it possible to construct the same thing with only one query? I have used $mess->data_seek(0); but its not helping because I didn't add my condition to the query.
Just go for PhP to filter your data instead of triple query your database. In this case you can figure out to go for this solution because you call 3 times your query with the same parameter :
$mess3 = $mysqli->prepare(" SELECT *
FROM ( SELECT cm.id ,
cm.userid,
cm.message,
cm.voteup,
cm.votedown,
cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ?
AND votedown - voteup >= 5
ORDER BY cm.date DESC LIMIT 30 ) ddd
ORDER BY date ASC ");
$mess3->bind_param("i", $room);
$mess3->execute();
$mess3->store_result();
$mess3->bind_result($chatid,$chat_userid ,$message,$voteup,$votedown ,$date);
while($row = $mess3->fetch()){
$voteup = $row['voteup'];
$votedown = $row['votedown'];
addToDiv1($row);
if( $voteup - $votedown >= 5 ) {
addToDiv2($row);
}
if( $votedown - $voteup >= 5 ) {
addToDiv3($row);
}
}
I will just give an answer based specifically on cleaning up your code. Technically you will still make the 3 calls in this scenario, but it will be cleaner because you include one function only, you don't see the script behind it.
As I mentioned, I am not an SQL aficionado so I can not give a good solution there (maybe you can use GROUP BY and perhaps an OR clause...I don't really know...). If I were to do this, I would do a function that can return all the options:
/core/functions/getChatMessages.php
function getChatMessages($settings,$mysqli)
{
$id = (!empty($settings['id']))? $settings['id'] : false;
$type = (!empty($settings['type']))? $settings['type'] : false;
$max = (!empty($settings['max']))? $settings['max'] : 30;
$mod = '';
// No id, just stop
if(!is_numeric($id))
return false;
// equation one
if($type == 'up')
$mod = ' AND voteup - votedown >= 5';
// equation two
elseif($type == 'down')
$mod = ' AND votedown - voteup >= 5';
$mess = $mysqli->prepare("SELECT * from ( SELECT cm.id ,cm.userid,cm.message,cm.voteup,cm.votedown,cm.date
FROM chat_messages cm
INNER JOIN members m ON m.id =cm.userid
INNER JOIN chat_settings cs ON cs.id = cm.room_id
WHERE cm.setting_id = ? {$mod}
ORDER BY cm.date DESC LIMIT {$max} ) ddd
ORDER BY date ASC");
$mess->bind_param("i", $id);
$mess->execute();
$mess->store_result();
$mess->bind_result($chatid, $chat_userid, $message, $voteup, $votedown, $date);
while($mess->fetch()){
$result[] = array(
'chatid'=>$chatid,
'chat_userid'=>$chat_userid,
'message'=>$message,
'voteup'=>$voteup,
'votedown'=>$votedown
);
}
// Send back the data
return (!empty($result))? $result : array();
}
To use:
// Include our handy function
require_once('/core/functions/getChatMessages.php');
// Store our id for use
$settings['id'] = 100;
// Should get 30 from first select
$voteGen = getChatMessages($settings,$mysqli);
// Should get 30 from second select
$settings['type'] = 'up';
$voteUp = getChatMessages($settings,$mysqli);
// Should get 15 from third select
// Just for the heck of it, I added in a limit settings
$settings['max'] = 15;
$settings['type'] = 'down';
$voteDown = getChatMessages($settings,$mysqli);
Now that you have these stored, just use a foreach loop to place them into your view. The good side of this is that you can call this where ever and when ever since the function only returns data. It allows you to work with the data in a view or non-view situation. Side note, I use PDO, so if there is something ineffective with the way the mysqli is fetching, that will be why. It's probably just best to fetch an assoc array to return...
I'm using the following 'DATE(time)' to get date from datetime and works with no errors.
SELECT * FROM $t WHERE owner = '$sn' && DATE(time) = '$d';
But then when tables are joint I attempt to use "p.DATE(time)" and I get this error.
FUNCTION p.DATE does not exist. Check the 'Function Name Parsing and Resolution'
Here's the full code where I use "p.DATE(time)".
function get_m_stats($con,$sn,$d=NULL,$t=NULL,$o=NULL){
$get_day = mysqli_query($con, "
SELECT m.* , COUNT(p.sid) frequency FROM music m
JOIN $t p
ON p.sid = m.sid
WHERE p.sid != '' AND p.owner = '$sn' AND p.DATE(time) = '$d'
AND m.perms = 'a'
GROUP BY m.sid
ORDER BY frequency $o
LIMIT 1") or die(mysqli_error($con));
$row_day = mysqli_fetch_array($get_day);
echo $row_day['title'];
}
How do I write this 'p.DATE(time)'?
you are assigning alias to function. just put it on column name
function get_m_stats($con,$sn,$d=NULL,$t=NULL,$o=NULL){
$get_day = mysqli_query($con, "
SELECT m.* , COUNT(p.sid) frequency FROM music m
JOIN $t p
ON p.sid = m.sid
WHERE p.sid != '' AND p.owner = '$sn' AND DATE(p.time) = '$d'
AND m.perms = 'a'
GROUP BY m.sid
ORDER BY frequency $o
LIMIT 1") or die(mysqli_error($con));
$row_day = mysqli_fetch_array($get_day);
echo $row_day['title'];
}
I am sure DATE() is a MySql function - so it cannot exist inside the tabular reference variable p.
Hence the correct way to get your data is getting p.time and then if you want to convert the dateTime to date, use the MySql function DATE.
Hence your query should be :
SELECT m.* , COUNT(p.sid)as frequency
FROM music m JOIN $t p
ON p.sid = m.sid
WHERE p.sid != ''
AND p.owner = '$sn'
AND DATE(p.time) = '$d'
AND m.perms = 'a'
GROUP BY m.sid
ORDER BY frequency $o
LIMIT 1
I have a query that returns close to a 1000 records. Using pagination, I'm showing a 100 records per page. Great...no problem. I can also sort by last name or first name in either ascending of descending order. ok so far. The first page returns records for last name starting with A to C. The problem I'm having is that when I click last name to descend I get records with last name starting with Z. The records at the end of my query, I want to get results going from C to A (what is shown on my first page...repeating the same functionality in each page.
Here is what I got...
$orderColumn = 'lastName';
$orderDirection = 'ASC';
if( isset($_POST["oc"]) && $_POST["oc"] !== '' ) { $orderColumn = $_POST["oc"]; }
if( isset($_POST["od"]) && $_POST["od"] !== '' ) { $orderDirection = $_POST["od"]; }
$per_page = 100;
$query = "SELECT * FROM table as t
LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID
LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID
WHERE t3.fk_utID = 7 and t.interviewed = 0";
$result = $db->query($query);
$count = mysql_num_rows($result);
$total = ceil($count/$per_page);
if ($_GET['page']) {
$page = $_GET['page'];
}
$offset = (($page-1)*$per_page);
$query2 = "SELECT firstName as first, lastName as last FROM table
LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID
LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID
WHERE t3.fk_utID = 7 and interviewed = 0 order by $orderColumn $orderDirection LIMIT $offset, $per_page";
$res = $db-> query($query2);
while($row = mysql_fetch_array($res)){
echo "<span style='display: inline-block; width: 15%;'>$row[first]</span>";
echo "<span style='display: inline-block; width: 15%;'>$row[last]</span>";
}
To what I was saying in comment.. BTW I'm on my mobile phone so this may be unformatted and or take a while...
Select what_you_need
From
( select your_inner_select
From table t
LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID
LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID
WHERE t3.fk_utID = 7 and interviewed = 0 LIMIT $offset, $per_page
ORDER BY $orderColumn ASC
)t
order by $orderColumn $orderDirection
I have created some filters in php.3 of them are aimming 1 table. The 4th is aimming another table.
first table is :
id_of_orders :
id_order(int) time(NOW) username(varchar) price(decimal)
the second one is :
order :
order_id(int) product(varchar) price (decimal)
order.order_id is refered to the id_of_orders.id_order
Table id_of_orders is like a mapper to the orders table (id_of_orders.id_order has unique numbers).
Table orders contains many orders some of them have same order_id
I want to return the id_of_orders.id_order which contain the order.product=='proion'
The query that i use is this:
$query = "SELECT * FROM id_of_orders WHERE 1=1";
if(!empty($_SESSION['employees']))
$query .= " AND id_of_orders.username='$_SESSION[employees]'";
if(!empty($_SESSION['timis']))
$query .= " AND id_of_orders.price='$_SESSION[timis]'";
if(!empty($_SESSION['dates']))
$query .= " AND DATE(time)='$_SESSION[dates]'";
//if(!empty($_SESSION['proions']))
// $query .= " AND (orders.product='$_SESSION[proions]' && id_of_orders.id_order==orders.order_id)";
$result = mysql_query($query);
You can try a query like
SELECT o.*
FROM id_of_orders i JOIN
(
SELECT order_id
FROM orders
WHERE product = 'proion'
GROUP BY order_id
) q ON i.id_order = q.order_id
WHERE o.username = ?
AND o.price = ?
AND DATE(time) = ?
or
SELECT i.id_order, i.time, i.username, i.price
FROM id_of_orders i JOIN orders o
ON i.id_order = o.order_id
WHERE 1 = 1
AND o.product = 'proion'
AND o.username = ?
AND o.price = ?
AND DATE(time) = ?
GROUP BY i.id_order, i.time, i.username, i.price