this my query
function get_transaksi_by_tgl($tgl_awal,$tgl_akhir,$limit, $offset = 0) {
$rs['query'] = $this->db->query("SELECT a.id_transaksi, a.nama, a.tgl_transaksi,
(SELECT COUNT( id_transaksi ) AS jum FROM tbl_detail_trs_menu WHERE id_transaksi = a.id_transaksi)
AS jumlah, a.status_transaksi, a.total, b.status_pelanggan, c.nama_karyawan FROM tbl_transaksi a
LEFT JOIN tbl_pelanggan b ON a.id_pelanggan = b.id_pelanggan LEFT JOIN tbl_karyawan c
ON a.id_karyawan = c.id_karyawan WHERE a.status_transaksi = 'OK' AND a.tgl_transaksi between ".$tgl_awal."
AND ".$tgl_akhir." LIMIT ".$offset.",".$limit."");
echo "jumlah : ".$rs['query']->num_rows();
return $rs;
}
but this query can't return rows....
whereas i try query in database can return 4 row... why??? thx u
Related
I have the code like this
$phql = "SELECT COUNT(a.id) FROM UserParkingIn a JOIN UserVehicle b ON a.userVehicleId = b.id WHERE b.vehicleTypeId = 1";
$result = $this->modelsManager->executeQuery($phql);
echo $result;
in UserParkingIn Table I have example id = 10, userVehicleId = 2
in UserVehicle Table I have example id =10, userVehicleId = 2, vehicleTypeId = 1
It return empty, but when I execute this query in phpMyAdmin I use this sql logic it return right number.
SELECT COUNT(a.id) FROM user_parking_in a JOIN user_vehicle b ON a.userVehicleId = b.id WHERE b.vehicleTypeId=1;
and it return number 7
Can someone explain why this return error?
Thank you.
I found the solution that id I used to count must set an alias to be like quota like this.
$query = $this->modelsManager->createQuery("SELECT COUNT(a.id) as quota FROM UserParkingIn a JOIN UserVehicle b ON a.userVehicleId = b.id WHERE a.ospoId = '$ospoId' ");
$records = $query->execute();
foreach($records as $record){
$parkingUsed = $record->quota;
}
and now it is working.
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...
Hi want to create a associative array for below query result :
$sql = "select s.*,di.dealsimage,
ctm.city,
l.location,
GROUP_CONCAT(DISTINCT cm.cuisine ORDER BY scr.cuisine_sequence_for_store) AS cui,
GROUP_CONCAT(DISTINCT rtm.restaurant_type ORDER BY srr.rest_type_sequence_for_store) AS restauranttype
from stores s
left join city_master ctm on s.city_id = ctm.city_id
left join locations l on s.location_id = l.location_id
left join store_cuisine_relation scr on s.store_id = scr.store_id
left join cuisine_master cm on scr.cuisine_id = cm.cuisine_id
left join store_resttype_relation srr on s.store_id = srr.store_id
left join restaurant_type_master rtm on rtm.rest_type_id = srr.rest_type_id
left join store_dealcat_relation sdr on s.store_id = sdr.store_id
left join deals_category_master dcm on dcm.deal_cat_id = sdr.deal_cat_id
left join deals_image di on di.`store_id` = s.store_id
where $condition1 s.is_active = 1 $condition2 group by (s.store_id) order by s.store_id";
//echo $sql;exit;
//echo $sql;exit;
$sqlex1 = mysqli_query($db,$sql);
$custom_count = #mysqli_num_rows($sqlex1); // it prints 28
while($result1 = mysqli_fetch_assoc($sqlex1)){
$dataArr = array_push_assoc($dataArr, 'store_id', $result1['store_id']);
$dataArr = array_push_assoc($dataArr, 'store_name', $result1['store_name']);
$dataArr = array_push_assoc($dataArr, 'store_logo', $result1['store_image_url']);
$dataArr = array_push_assoc($dataArr, 'deals_image', $result1['dealsimage']);
}
//echo count($dataArr);exit;
//echo $kl;exit;
//$result = array_merge_recursive($gpsArr,$dataArr);
function array_push_assoc($array, $key, $value){
$array[$key][] = $value;
return $array;
}
The query returns 28 result but when I try to echo the count of $dataArr it prints 4 always. What im doing wrong ? How can I achieve this ?
Thanks in advance
Becasue your function array_push_assoc() creates array with 4 keys store_id, store_name,store_logo, anddeals_image`, and each key has 28 rows
Try this:
dataArr = array();
while($result1 = mysqli_fetch_assoc($sqlex1))
{
$dataArr[] = array('store_id'=>$result1['store_id'],
'store_name'=>$result1['store_name'],
'store_logo'=>$result1['store_image_url'],
'deals_image'=>$result1['dealsimage']);
}
This will create array with 28 associative arrays
Your code should be changed to:
while($result1 = mysqli_fetch_assoc($sqlex1))
{
array_push($dataArr, array ('store_id'=> $result1['store_id'], 'store_name'=> $result1['store_name'], 'store_logo'=> $result1['store_image_url'], 'deals_image'=> $result1['dealsimage']));
}
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
Writing a custom module trying to look up comments. I have a SQL statement as follows:
$client_comment = db_query("SELECT comment.subject AS comment_subject,
comment.cid AS cid,
comment.nid AS comment_nid,
comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
INNER JOIN {field_data_field_associated_client} associated_client ON comment.cid = associated_client.entity_id
WHERE (( (associated_client.field_associated_client_nid = '$nid')
OR (comment.nid = '$nid') )
AND (comment.status <> '0')
AND (node_comment.status = '1') )
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
Ideally, this is supposed to return the following:
However, I get the following:
For some reason, it is only returning the "associated_client" result instead of the "comment.nid" result. Here is the full statement I'd like to get working. I know it's a SMH moment, but any help would be great.
Per request, here is the code I'm using to cycle through the returning array:
foreach($client_comment as $item) {
print_r($item);
print '<br /><br />';
}
Here are 2 queries that print all of the data to the screen separately. I want to combine these two queries in to 1 query:
$client_comment = db_query("SELECT comment.subject AS comment_subject, comment.cid AS cid, comment.nid AS comment_nid, comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
WHERE (( (comment.status <> '0') AND (node_comment.status = '1') AND (comment.nid = '$nid') ))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
// Get the comments associated TO the client from Caregiver node.
$client_associated_comment = db_query("SELECT comment.subject AS comment_subject, comment.cid AS cid, comment.nid AS comment_nid, comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
INNER JOIN {field_data_field_associated_client} associated_client ON comment.cid = associated_client.entity_id
WHERE (( (comment.status <> '0') AND (node_comment.status = '1') AND (associated_client.field_associated_client_nid = '$nid') ))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
foreach($client_comment as $item) {
$client_comment_array[] = $item;
}
foreach ($client_associated_comment as $item) {
$client_comment_array[] = $item;
}
foreach($client_comment_array as $item) {
print_r($item);
print '<br /><br />';
}
Alright, I solved it by using LEFT JOIN instead of INNER JOIN. Resulting query:
$client_comment = db_query("SELECT comment.subject AS comment_subject,
comment.cid AS cid,
comment.nid AS comment_nid,
comment.created AS comment_created
FROM
{comment} comment
INNER JOIN {node} node_comment ON comment.nid = node_comment.nid
LEFT JOIN {field_data_field_associated_client} associated_client ON comment.cid = associated_client.entity_id
WHERE (( (associated_client.field_associated_client_nid = '$nid')
OR (comment.nid = '$nid') )
AND (comment.status <> '0')
AND (node_comment.status = '1') )
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0");
foreach($client_comment as $item) {
print_r($item);
print '<br /><br />';
}