MySQL select last image in LEFT JOIN - php

I have this function that lists the first inserted image and other data from accommodation database.
function getLIST($sort_by,$saved=0,$filter)
{
$session = JFactory::getSession();
$lang =& JFactory::getLanguage();
$query = "SELECT a.id FROM #__jomholiday_fields AS a where a.name='COM_JOMHOLIDAY_ACCOMODATION_RATING'";
$db = $this->getDbo();
$db->setQuery( $query );
$rating_id = $db->loadResult();
$query = "SELECT a.id FROM #__jomholiday_fields AS a where a.name='COM_JOMHOLIDAY_BOARD_BASIS'";
$db->setQuery( $query );
$board_basis_id = $db->loadResult();
$query = $db->getQuery(true);
$listing_expiry_days=(int)$this->getConf("listing_expiry_days");
if($listing_expiry_days)
{
$now=strtotime("now");
$temp=$now-$listing_expiry_days*(60*60*12);
$toold=date('Y-m-d',$temp);
}
else $toold=0;
$search_mod=0;
$query->select(
$this->getState(
'list.select',
'a.id, a.categories_id, a.number, a.headline, a.short_description, a.lat, a.lon, a.published, a.dpublished' .
', a.featured, a.address_name, a.created, a.modified, p.name , a.price_night, a.price_week, a.sleeps'
)
);
$query->from('#__jomholiday_listings AS a');
$query->select('p.name AS image');
$query->select('MAX(p.id)');
$query->join('LEFT', '#__jomholiday_photos AS p ON p.listings_id = a.id AND (p.rooms_id=0 OR p.rooms_id IS NULL) ');
$query->select('ac.name AS category_name');
$query->select('ac.rental AS price_type');
$query->join('LEFT', '#__jomholiday_categories AS ac ON ac.id = a.categories_id');
$query->where("(ac.lang='".$lang->getTag()."' OR ac.lang='*')");
//$query->where("p.id = MAX(p.id)");
$query->select('AVG(r.rating) AS rating_average');
$query->join('LEFT', '#__jomholiday_reviews AS r ON r.published="1" AND r.listingid=a.id');
if ($rating_id){
$query->select('f1.value AS accomodation_rating');
$query->join('LEFT', '#__jomholiday_listings_to_fields AS f1 ON f1.listings_id = a.id AND f1.fields_id='.$rating_id.'');
}
if ($board_basis_id){
$query->select('f2.value AS all_inclusive');
$query->join('LEFT', '#__jomholiday_listings_to_fields AS f2 ON f2.listings_id = a.id AND f2.fields_id='.$board_basis_id.' and f2.value="COM_JOMHOLIDAY_ALL_INCLUSIVE"');
$query->select('f3.value AS bed_breakfast');
$query->join('LEFT', '#__jomholiday_listings_to_fields AS f3 ON f3.listings_id = a.id AND f3.fields_id='.$board_basis_id.' and f3.value="COM_JOMHOLIDAY_BED_BREAKFAST"');
$query->select('f4.value AS full_board');
$query->join('LEFT', '#__jomholiday_listings_to_fields AS f4 ON f4.listings_id = a.id AND f4.fields_id='.$board_basis_id.' and f4.value="COM_JOMHOLIDAY_FULL_BOARD"');
$query->select('f5.value AS half_board');
$query->join('LEFT', '#__jomholiday_listings_to_fields AS f5 ON f5.listings_id = a.id AND f5.fields_id='.$board_basis_id.' and f5.value="COM_JOMHOLIDAY_HALF_BOARD"');
$query->select('f6.value AS room_only');
$query->join('LEFT', '#__jomholiday_listings_to_fields AS f6 ON f6.listings_id = a.id AND f6.fields_id='.$board_basis_id.' and f6.value="COM_JOMHOLIDAY_ROOM_ONLY"');
$query->select('f7.value AS self_cattering');
$query->join('LEFT', '#__jomholiday_listings_to_fields AS f7 ON f7.listings_id = a.id AND f7.fields_id='.$board_basis_id.' and f7.value="COM_JOMHOLIDAY_SELF_CATTERING"');
}
if ($saved)
{
$cids=JRequest::getString('savedlist', '', 'cookie');
$cid=explode(",",$cids);
JArrayHelper::toInteger($cid);
$cids=implode(",",$cid);
$query->where('a.id IN ( '. $cids .' )');
$search_mod=1;
}
$query->where("a.published='1'");
$query->where("a.approved='1'");
if ($toold) $query->where("a.dpublished>'$toold'");
if ($session->get('jom_zlat')!=null)
{
$lat1=(float)$session->get('jom_lat')-$session->get('jom_zlat');
$lat2=(float)$session->get('jom_lat')+$session->get('jom_zlat');
$lon1=(float)$session->get('jom_lon')-$session->get('jom_zlon');
$lon2=(float)$session->get('jom_lon')+$session->get('jom_zlon');
if ($lat1>$lat2){$temp=$lat1;$lat1=$lat2;$lat2=$temp;}
if ($lon1>$lon2){$temp=$lon1;$lat1=$lon2;$lon2=$temp;}
if ($lat1) $query->where("a.lat>".$lat1);
if ($lat2) $query->where("a.lat<".$lat2);
if ($lon1) $query->where("a.lon>".$lon1);
if ($lon2) $query->where("a.lon<".$lon2);
$search_mod=1;
}
if ($session->get('jom_address_select')!=null)
{
$temp=explode(",",$session->get('jom_address_select'));
if ($temp[0]) $temp1=$this->getRegion((int)$temp[0]);
if ($temp[1]) $temp1.=", ".$this->getRegion((int)$temp[1]);
if ($temp[2]) $temp1.=", ".$this->getRegion((int)$temp[2]);
$query->where("(a.address_name like '%".str_replace("'","\'",$temp1)."%')", ENT_QUOTES);
$search_mod=1;
}
if (str_replace(",","",$session->get('jom_booking')))
{
$temp=explode(",",$session->get('jom_booking'));
if ($temp[0] && $temp[2]>0)
{
$in=strtotime($temp[0]);
$out=strtotime($temp[1]);
$query->where("a.sleeps >= '".(int)$temp[2]."'");
while ($in<$out)
{
$query->where("(a.booking LIKE '%,".date("ymd",$in)."-".(int)$temp[2].",%' OR a.booking NOT LIKE '%,".date("ymd",$in)."-%' OR a.booking IS NULL)");
$in=strtotime('+1 day', $in);
}
}
$search_mod=1;
}
if ((int)$session->get('jomholiday_search_cat'))
{
$temp=explode(",",$session->get('jomholiday_search_cat'));
JArrayHelper::toInteger($temp);
$cidss = implode( ',', $temp );
$query->where("a.categories_id IN ( ". $cidss ." )");
$search_mod=1;
}
if ($session->get('jom_title')!=null){$search_mod=1; $query->where("(a.headline like '%".str_replace("'","\'",$session->get('jom_title'))."%' OR a.address_name like '%".str_replace("'","\'",$session->get('jom_title'))."%')", ENT_QUOTES);}
if ((int)$session->get('jom_pricemin')!=null){$search_mod=1; $query->where("a.price_night>=".(int)$session->get('jom_pricemin'));}
if ((int)$session->get('jom_pricemax')!=null) {$search_mod=1;$query->where("a.price_night<=".(int)$session->get('jom_pricemax'));}
if ($session->get('jomholiday_search'))
{
$val=json_decode($session->get('jomholiday_search'),true);
if (is_array($val))
{
$array_keys = array_keys($val);
foreach($array_keys as $key) if ($val[$key]!=null)
{
if (is_array($val[$key]))
{
$array_keys1 = array_keys($val[$key]);
foreach($array_keys1 as $key1)
{
$val[$key][$key1]=htmlspecialchars($val[$key][$key1],ENT_QUOTES);
$query->where('exists(select 1 from #__jomholiday_listings_to_fields AS fs'.$key.'_'.$key1.' where fs'.$key.'_'.$key1.'.listings_id = a.id AND fs'.$key.'_'.$key1.'.value="'.$val[$key][$key1].'" and fs'.$key.'_'.$key1.'.fields_id='.$key.')');
}
}
else if (trim($val[$key])!=null)
{
$val[$key]=htmlspecialchars(trim($val[$key]),ENT_QUOTES);
$query->where('exists(select 1 from #__jomholiday_listings_to_fields AS fs'.$key.' where fs'.$key.'.listings_id = a.id AND fs'.$key.'.value="'.$val[$key].'" and fs'.$key.'.fields_id='.$key.')');
}
}
$search_mod=1;
}
}
if ((int)JRequest::getVar('cid') && !$search_mod) $query->where("a.categories_id='".(int)JRequest::getVar('cid')."'");
if ((int)$session->get('jom_pricemin_f')!=null) $query->where("a.price_night>=".(int)$session->get('jom_pricemin_f'));
if ((int)$session->get('jom_pricemax_f')!=null) $query->where("a.price_night<=".(int)$session->get('jom_pricemax_f'));
if ($session->get('jomholiday_filter'))
{
$val=json_decode($session->get('jomholiday_filter'),true);
if (is_array($val))
{
$array_keys = array_keys($val);
foreach($array_keys as $key) if ($val[$key]!=null)
{
if (is_array($val[$key]))
{
$array_keys1 = array_keys($val[$key]);
foreach($array_keys1 as $key1)
{
$val[$key][$key1]=htmlspecialchars($val[$key][$key1],ENT_QUOTES);
$query->where('exists(select 1 from #__jomholiday_listings_to_fields AS fsf'.$key.'_'.$key1.' where fsf'.$key.'_'.$key1.'.listings_id = a.id AND fsf'.$key.'_'.$key1.'.value="'.$val[$key][$key1].'" and fsf'.$key.'_'.$key1.'.fields_id='.$key.')');
}
}
else if (trim($val[$key])!=null)
{
$val[$key]=htmlspecialchars(trim($val[$key]),ENT_QUOTES);
$query->where('exists(select 1 from #__jomholiday_listings_to_fields AS fsf'.$key.' where fsf'.$key.'.listings_id = a.id AND fsf'.$key.'.value="'.$val[$key].'" and fsf'.$key.'.fields_id='.$key.')');
}
}
}
}
if ($session->get('jom_address')!=null) $query->where("a.address_name like '".str_replace("'","\'",$session->get('jom_address'))."%'", ENT_QUOTES);
$query->group("a.id");
if ($this->getState('sort_by')=="a.created DESC") $order_s=$this->getState('sort_by');
elseif ($this->getState('sort_by')=="a.modified DESC") $order_s=$this->getState('sort_by');
elseif ($this->getState('sort_by')=="a.price_night DESC") $order_s=$this->getState('sort_by');
elseif ($this->getState('sort_by')=="a.price_night") $order_s=$this->getState('sort_by');
elseif ($this->getState('sort_by')=="a.headline") $order_s=$this->getState('sort_by');
else $order_s="";
if ($this->getConf(premium_first))
{
if ($order_s && JRequest::getVar('task')!='rss') $query->order("a.featured desc, ".$order_s.",id desc");
else $query->order("a.featured desc, a.created DESC, id desc");
}
else
{
if ($order_s && JRequest::getVar('task')!='rss') $query->order($order_s.",id desc");
else $query->order("a.created DESC, id desc");
}
if ($saved || JRequest::getVar('task')=='rss') $data = $this->_getList($query);
else $data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
//echo $query;
return $data;
}
I need to retrive last inserted image from table #__jomholiday_photos. As you can see I did try to put the MAX(p.id) but that didn't helped.
I did try to put the $query->order("p.id DESC"); , that didn't helped aether.
Update:
Here is a query that is generated with this code
SELECT a.id, a.categories_id, a.number, a.headline, a.short_description, a.lat, a.lon,
a.published, a.dpublished, a.featured, a.address_name, a.created, a.modified,
p.name , a.price_night, a.price_week, a.sleeps,p.name AS image,MAX(p.id),ac.name AS category_name,
ac.rental AS price_type,AVG(r.rating) AS rating_average,f1.value AS accomodation_rating,
f2.value AS all_inclusive,f3.value AS bed_breakfast,f4.value AS full_board,f5.value AS half_board,
f6.value AS room_only,f7.value AS self_cattering
FROM #__jomholiday_listings AS a
LEFT JOIN #__jomholiday_photos AS p ON p.listings_id = a.id AND (p.rooms_id=0 OR p.rooms_id IS NULL)
LEFT JOIN #__jomholiday_categories AS ac ON ac.id = a.categories_id
LEFT JOIN #__jomholiday_reviews AS r ON r.published="1" AND r.listingid=a.id
LEFT JOIN #__jomholiday_listings_to_fields AS f1 ON f1.listings_id = a.id
AND f1.fields_id=22
LEFT JOIN #__jomholiday_listings_to_fields AS f2 ON f2.listings_id = a.id
AND f2.fields_id=10
and f2.value="COM_JOMHOLIDAY_ALL_INCLUSIVE" LEFT JOIN #__jomholiday_listings_to_fields AS f3
ON f3.listings_id = a.id AND f3.fields_id=10 and f3.value="COM_JOMHOLIDAY_BED_BREAKFAST"
LEFT JOIN #__jomholiday_listings_to_fields AS f4 ON f4.listings_id = a.id
AND f4.fields_id=10
and f4.value="COM_JOMHOLIDAY_FULL_BOARD" LEFT JOIN #__jomholiday_listings_to_fields AS f5
ON f5.listings_id = a.id AND f5.fields_id=10 and f5.value="COM_JOMHOLIDAY_HALF_BOARD"
LEFT JOIN #__jomholiday_listings_to_fields AS f6 ON f6.listings_id = a.id
AND f6.fields_id=10
and f6.value="COM_JOMHOLIDAY_ROOM_ONLY" LEFT JOIN #__jomholiday_listings_to_fields AS f7
ON f7.listings_id = a.id AND f7.fields_id=10 and f7.value="COM_JOMHOLIDAY_SELF_CATTERING"
WHERE (ac.lang='hr-HR' OR ac.lang='*')
AND a.published='1' AND a.approved='1'
GROUP BY a.id
ORDER BY a.featured desc, a.headline,id desc LIMIT 0, 15
'p.name' retrieves the firs record from '#__jomholiday_photos'. I need the last one of each listings.

I founded how to get the last image by replacing this code:
$query->join('LEFT', '#__jomholiday_photos AS p ON p.listings_id = a.id AND (p.rooms_id=0 OR p.rooms_id IS NULL) ');
with this one:
$query->join('LEFT', '( SELECT MAX(id) as maxpid , name, listings_id, rooms_id FROM #__jomholiday_photos GROUP BY id ORDER BY id DESC) AS p ON p.listings_id = a.id AND (p.rooms_id=0 OR p.rooms_id IS NULL) ');

Related

Multiple IN operator mysql combine

I would like to ask can I combine multiple IN operator with AND query?I need your help with my codes.Here is my code that I have tried but not working.
if ($areas != '' || $city_check != '' || $course != '' || $subject_check != '') {
$countcity = count($city_check);
$countsubject = count($subject_check);
$area_ids = implode(',',$city_check);
$subject_ids = implode(',',$subject_check);
$sql .= "AND TAC.tac_st_id = '".$areas."' AND TAC.tac_city_id IN($area_ids)
AND TRS.trs_tc_id = '".$course."' AND TRS.trs_ts_id IN($subject_ids)
GROUP BY U.u_username
HAVING COUNT(distinct TAC.tac_city_id) = '".$countcity."' COUNT(distinct TRS.trs_ts_id) = '".$countsubject."'
";
}
It produce no result.
I have done below code that working like I want but it can only run each blocks inside if.So if I want to search for city_check, the subject_check will not working and vice versa.
//search for cities
// if ($areas != '' || $city_check != '') {
// $countcity = count($city_check);
// $sql .= "AND TAC.tac_st_id = '".$areas."' AND TAC.tac_city_id IN(".implode(',',$city_check).")
// GROUP BY U.u_username
// HAVING COUNT(distinct TAC.tac_city_id) = '".$countcity."'
// ";
// }
//search for subject
// if ($course != '' || $subject_check != '') {
// $countsubject = count($subject_check);
// // echo json_encode(["message"=>$countcity]);
// $sql .= "AND TRS.trs_tc_id = '".$course."' AND TRS.trs_ts_id IN(".implode(',',$subject_check).")
// GROUP BY U.u_username
// HAVING COUNT(distinct TRS.trs_ts_id) = '".$countsubject."'
// ";
// }
What I want is that both cities and subject can be search together.Thank you for your help in advanced..
Edit: I try to output my SQL in phpmyadmin
SELECT U.u_username,U.u_email,U.u_status,ST.st_name,CT.city_name,TC.tc_title,TS.ts_title
FROM tk_user as U
INNER JOIN tk_user_details AS UD ON UD.ud_u_id = U.u_id
LEFT JOIN tk_tutor_subject AS TRS ON TRS.trs_u_id = U.u_id
LEFT JOIN tk_tution_course AS TC ON TC.tc_id = TRS.trs_tc_id
LEFT JOIN tk_tution_subject AS TS ON TS.ts_id = TRS.trs_ts_id
LEFT JOIN tk_tutor_area_cover AS TAC ON TAC.tac_u_id = U.u_id
LEFT JOIN tk_cities CT ON CT.city_id = UD.ud_city AND TAC.tac_city_id = CT.city_id
LEFT JOIN tk_states AS ST ON TAC.tac_st_id = ST.st_id
LEFT JOIN tk_countries AS C ON ST.st_c_id = C.c_id AND CT.city_c_id = C.c_id
WHERE U.u_status <> 'D'
AND TAC.tac_st_id = 1046 AND TAC.tac_city_id IN(16,17)
AND TRS.trs_tc_id = 5 AND TRS.trs_ts_id IN(8,9)
GROUP BY U.u_username
HAVING COUNT(distinct TAC.tac_city_id) = 2 AND COUNT(distinct TRS.trs_ts_id) = 2
If one of them could be empty you should use something like that:
Use OR
...
WHERE U.u_status <> 'D'
AND
(
(TAC.tac_st_id = 1046 AND TAC.tac_city_id IN(16,17) )
OR
(TRS.trs_tc_id = 5 AND TRS.trs_ts_id IN(8,9) )
)
...

Warning: mssql_query(): message: Invalid object name 'Consignment'. (severity 16)

I need your guidance. i created an API in slim framework with mssql and php. It was working ok but now it display an error when i check on postman. i have attached error screenshot below. please help me out .
$app->post('/tracking', function ($request) use ($app){
$params_tracking = $request->getBody();
$params_tracking = json_decode($params_tracking);
global $connTrack;
$consignment = $params_tracking->data;
$strsql = <<<SQL
SELECT
c.consignmentNumber,
c.pieces,
c.consigner,
c.consignee consignee,
CONVERT(VARCHAR(10), c.bookingDate, 105) bookingDate,
c.weight,
c.serviceTypeName,
r.receivedBy ReceivedBy,
case when cth.reason is null then ( CASE WHEN r.CurrentStatus IS
NULL THEN s.TrackingStatus ELSE r.CurrentStatus END )
else cth.reason end CurrentStatus,
DeliveryTime,bb.name Destination,c.consignerAccountNo
AccoutNo,b.name orign,r.delievryRider delievryRider
FROM Consignment c
INNER JOIN Branches bb ON c.destination = bb.branchCode
INNER JOIN Branches b ON c.orgin = b.branchCode
LEFT JOIN (
SELECT rc.consignmentNumber,
max(rc.receivedBy) ReceivedBy,
max(rc.Status) CurrentStatus,
max(rc.deliveryDate) DeliveryTime,
max(r.firstName + ' (' + rrs.riderCode + ' )')
delievryRider
FROM RunsheetConsignment rc,
Riders r,
RiderRunsheet rrs,
ExpressCenters ec
WHERE rc.runsheetNumber = rrs.runsheetNumber
AND rrs.riderCode = r.riderCode
AND rrs.expIdTemp = r.expressCenterId
AND rrs.expIdTemp = ec.expressCenterCode
AND ec.bid = rc.branchcode
GROUP BY rc.consignmentNumber
) r
ON c.consignmentnumber = r.consignmentNumber
INNER JOIN (
SELECT MAX(t.id) ID,t.consignmentNumber
FROM ConsignmentsTrackingHistory t
GROUP BY t.consignmentNumber
)
ct ON ct.consignmentNumber = c.consignmentNumber
INNER JOIN ConsignmentsTrackingHistory AS cth
ON cth.id = ct.ID
INNER JOIN MNP_ConsginmentTrackingStatus AS s
ON s.StatusID = cth.stateID
WHERE c.consignmentNumber = '$consignment' and
c.consignerAccountNo not in
('4B45','7240','4H86','4H87',
'4H88','4B87','7240','4B45','4H91',
'4H89','4H90','4F47');
SQL;
$result_track = mssql_query( $strsql,$connTrack );
$num_rows = mssql_num_rows($result_track);
if ($num_rows > 0){
while($row = mssql_fetch_assoc($result_track)){
$track = array(); //create the array
$tracking_array['cn_no'] = $consignment;
$tracking_array['book_date'] = $row['bookingDate'];
$tracking_array['service_type'] = $row['serviceTypeName'];
$tracking_array['origin'] = $row['orign'];
$tracking_array['destination'] = $row['Destination'];
$tracking_array['status'] = $row['CurrentStatus'];
$tracking_array['delivery_date'] = $row['DeliveryTime'];
$tracking_array['received_by'] = $row['ReceivedBy'];
array_push($track,$tracking_array);
}
echo json_encode($track);
}
});

how to group by after the Where function into this query?

Hello folks I want to sort books by min and max price but I dont know where I will add the group by function after the WHERE ? here is the query
$sql = "SELECT DISTINCT bk.title AS Title, YEAR(bk.date_released) AS Year, bk.price AS Price, cat.name AS Category, aut.name AS Author FROM books bk
JOIN books_authors bk_aut
ON bk_aut.book_id = bk.id
JOIN authors aut
ON aut.id = bk_aut.author_id
JOIN books_categories bk_cat
ON bk_cat.book_id = bk.id
JOIN categories cat
ON cat.id = bk_cat.cat_id
JOIN books_locations bk_loc
ON bk_cat.book_id = bk.id
JOIN locations loc
ON loc.id = bk_loc.loc_id
";
if (isset($_GET['srch_for'])){
$locations = array();
$getters = array();
$queries = array();
foreach($_GET as $key => $value) {
$temp = is_array($value) ? $value : intval(trim($value));
if (!empty($temp)) {
list($key) = explode("-",$key);
if ($key == 'srch_locations'){
array_push($locations,$value);
}
if (!in_array($key,$getters)){
$getters[$key] = intval(trim($value));
}
}
}
if (!empty($locations)) {
$loc_qry = implode(",",$locations);
}
if(!empty($getters)) {
foreach($getters as $key => $value){
${$key} = $value;
switch($key) {
case 'srch_for':
array_push($queries, "(bk.title LIKE '%$srch_for%' || bk.description LIKE '%$srch_for%' || bk.isbn LIKE '%$srch_for%')");
case 'srch_author':
array_push($queries, "bk_aut.author_id = $srch_author");
break;
case 'srch_language':
array_push($queries, "bk_cat.cat_id = $srch_category");
break;
case 'srch_locations':
array_push($queries, "bk_loc.location_id IN ($loc_qry)");
break;
}
}
}
if(!empty($queries)) {
$sql .= " WHERE ";
$i=1;
foreach($queries as $query) {
if ($i < count($queries)) {
$sql .= $query." AND ";
}else{
$sql .= $query;
}
$i++;
}
}
$sql .= " ORDER BY bk.title ASC";
}
Run code s
I am beginner in php and I cant learn through listening because I am deaf which you help me guys thank you in advance
SELECT Title,Year, sum(Price) AS Price, Category,Author
FROM
(
SELECT DISTINCT bk.title AS Title, YEAR(bk.date_released) AS Year, bk.price AS Price, cat.name AS Category, aut.name AS Author
FROM books bk
JOIN books_authors bk_aut
ON bk_aut.book_id = bk.id
JOIN authors aut
ON aut.id = bk_aut.author_id
JOIN books_categories bk_cat
ON bk_cat.book_id = bk.id
JOIN categories cat
ON cat.id = bk_cat.cat_id
JOIN books_locations bk_loc
ON bk_cat.book_id = bk.id
JOIN locations loc
ON loc.id = bk_loc.loc_id
)T
Group By Title,Year, Category,A
You can use Sub query Like This..

Binding multiple arrays in pdo

There are 3 different filters: books, authors and stores (select lists), and I may use their all together at once or only one or two of them, so I use UNION to get together all queries
require('database.php');
if(isset($_POST['books'])){
$books_ids = $_POST["books"];
}
if(isset($_POST['authors'])){
$authors_ids = $_POST["authors"];
}
if(isset($_POST['stores'])){
$stores_ids = $_POST["stores"];
}
$query = "";
if( !empty( $books_ids ))
{
$books_ids_in = implode(',', array_fill(0, count($books_ids), '?'));
$query .= "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'book' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (". $books_ids_in .")
GROUP BY b.id
ORDER BY b.id";
}
if( !empty( $authors_ids ) )
{
$authors_ids_in = implode(',', array_fill(0, count($authors_ids), '?'));
if (!empty($query)) {
$query .= " UNION ";
}
$query .= "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'author' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (
SELECT DISTINCT book_id FROM books_authors WHERE author_id IN (". $authors_ids_in .")
)
GROUP BY b.id
ORDER BY b.id";
}
if( !empty( $stores_ids ) )
{
$stores_ids_in = implode(',', array_fill(0, count($stores_ids), '?'));
if (!empty($query)) {
$query .= " UNION ";
}
$query .= "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'store' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id
WHERE
b.id IN (
SELECT DISTINCT book_id FROM books_stores WHERE store_id IN (". $stores_ids_in .")
)
GROUP BY b.id
ORDER BY b.id";
}
if( !empty( $query )) {
$stmt = $conn->prepare($query);
if( !empty( $books_ids ))
{
foreach ($books_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
}
if( !empty( $authors_ids ))
{
foreach ($authors_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
}
if( !empty( $stores_ids ))
{
foreach ($stores_ids as $k => $id) {
$stmt->bindValue(($k+1), $id);
}
}
$stmt->execute();
$results = $stmt->fetchAll();
echo json_encode($results);
}
$conn = null;
code works just fine when I use only one filter, but when I try to use 2 or more, I get error
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in C:\xampp\htdocs\bookstore\filter.php:123 Stack trace: #0 C:\xampp\htdocs\bookstore\filter.php(123): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\bookstore\filter.php on line 123
I guess, something's wrong with bindValue using but I don't know how to fix that?
UPD
var_dump($query) (3 books and 2 authors chosen)
string(1097) "SELECT b.id, b.name, b.year, GROUP_CONCAT(DISTINCT a.name) AS author_names, GROUP_CONCAT(DISTINCT s.name) AS store_names, 'book' as param FROM books AS b LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id LEFT JOIN authors AS a ON a.id = b_a.author_id LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id LEFT JOIN stores AS s ON s.id = b_s.store_id WHERE b.id IN (?,?,?) GROUP BY b.id ORDER BY b.id UNION SELECT b.id, b.name, b.year, GROUP_CONCAT(DISTINCT a.name) AS author_names, GROUP_CONCAT(DISTINCT s.name) AS store_names, 'author' as param FROM books AS b LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id LEFT JOIN authors AS a ON a.id = b_a.author_id LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id LEFT JOIN stores AS s ON s.id = b_s.store_id WHERE b.id IN ( SELECT DISTINCT book_id FROM books_authors WHERE author_id IN (?,?) ) GROUP BY b.id ORDER BY b.id" 01201
There are problems with your code for building a dynamic query.
When building a dynamic query you need to separate those parts of the query that are static from those that are dynamic.
You can see that the following code is static.
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'book' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id ";
And also
" GROUP BY b.id
ORDER BY b.id";
The rest of the code is dynamic.
When filtering records the WHERE clause is used and the AND & OR operators are used to filter records based on more than one condition.
The AND operator displays a record if both the first condition AND the second condition are true.
The OR operator displays a record if either the first condition OR the second condition is true.
so for the first condition WHERE is used but after that AND or OR must be used(using OR in your example)
// Static code
sql = "SELECT * FROM `table`"
// Set initial condition to WHERE
clause = "WHERE";
if( !empty( filter )){
Add clause to sql
Add condition to sql
change clause to OR or AND as required
}
Repeat for each filter
Note the filter is not changed until a filter is not empty and remains changed once changed.
The remaining static code is added after all the filters have been handled
To allow different filters to be applied you can use a flag.
$flag = 0;
if(isset($_POST['books'])){
$books_ids = $_POST["books"];
$flag += 1;
}
if(isset($_POST['authors'])){
$authors_ids = $_POST["authors"];
$flag += 10;
}
if(isset($_POST['stores'])){
$stores_ids = $_POST["stores"];
$flag += 100;
}
Use "lazy" binding when possible - passing data into execute will dramatically shorten your code.
See PDO info
You require to merge array to perform this. Using switch statement with the flag you merge the arrays required.
switch ($flag) {
case 1:
$param_array = $books_ids;
break;
case 10:
$param_array = $authors_ids;
break;
case 100:
$param_array = $stores_ids;
break;
case 11://books & authors
$param_array = array_merge($books_ids, $authors_ids);
break;
case 101://books & stores
$param_array = array_merge($books_ids, $stores_ids);
break;
case 110://authors & stores
$param_array = array_merge($authors_ids, $stores_ids);
break;
case 111://books & authors & stores
$param_array = array_merge(array_merge($books_ids,$authors_ids),$stores_ids);
break;
}
if( !empty( $query )) {
$stmt = $conn->prepare($query);
$stmt->execute($param_array);
$results = $stmt->fetchAll();
echo json_encode($results);
}
The following code uses the above points. I have echoed some lines to indicate results which can be removed once testing is done.Also some code has been commented out for testing.
//Set flag
$flag = 0;
if(isset($_POST['books'])){
$books_ids = $_POST["books"];
$flag += 1;
}
if(isset($_POST['authors'])){
$authors_ids = $_POST["authors"];
$flag += 10;
}
if(isset($_POST['stores'])){
$stores_ids = $_POST["stores"];
$flag += 100;
}
echo $flag. " <BR>";//Remove after testing
//Basic SQL statement
$query = "SELECT
b.id,
b.`name`,
b.`year`,
GROUP_CONCAT(DISTINCT a.`name`) AS author_names,
GROUP_CONCAT(DISTINCT s.`name`) AS store_names,
'book' as param
FROM
books AS b
LEFT JOIN books_authors AS b_a ON b.id = b_a.book_id
LEFT JOIN authors AS a ON a.id = b_a.author_id
LEFT JOIN books_stores AS b_s ON b.id = b_s.book_id
LEFT JOIN stores AS s ON s.id = b_s.store_id ";
// Set initial condition to WHERE
$clause = "WHERE";
if( !empty( $books_ids ))
{
$books_ids_in = implode(',', array_fill(0, count($books_ids), '?'));
$query .= $clause;
$query .= " b.id IN (". $books_ids_in .")";
// Set condition to OR for additional condition
$clause = " OR ";
}
if( !empty( $authors_ids ) )
{
$authors_ids_in = implode(',', array_fill(0, count($authors_ids), '?'));
/* This part commented out as I don't see relevance
if (!empty($query)) {
$query .= " UNION ";
}
*/
$query .= $clause;
$query .= " b.id IN (
SELECT DISTINCT book_id FROM books_authors WHERE author_id IN (". $authors_ids_in .")
)";
// Set condition to OR for additional condition
$clause = " OR ";
}
if( !empty( $stores_ids ) )
{
$stores_ids_in = implode(',', array_fill(0, count($stores_ids), '?'));
/* if (!empty($query)) {
$query .= " UNION ";
}
*/
$query .= $clause;
$query .= " b.id IN (
SELECT DISTINCT book_id FROM books_stores WHERE store_id IN (". $stores_ids_in .")
)";
$clause = " OR ";
}
//Add GROUP & ORDER
$query .= " GROUP BY b.id
ORDER BY b.id";
echo $query; //Remove after testing
//building $param_array
switch ($flag) {
case 1:
$param_array = $books_ids;
break;
case 10:
$param_array = $authors_ids;
break;
case 100:
$param_array = $stores_ids;
break;
case 11://books & authors
$param_array = array_merge($books_ids, $authors_ids);
break;
case 101://books & stores
$param_array = array_merge($books_ids, $stores_ids);
break;
case 110://authors & stores
$param_array = array_merge($authors_ids, $stores_ids);
break;
case 111://books & authors & stores
$param_array = array_merge(array_merge($books_ids,$authors_ids),$stores_ids);
break;
}
echo "<br>";
print_r($param_array);// remove after testing
/*
if( !empty( $query )) {
$stmt = $conn->prepare($query);
$stmt->execute($param_array);
$results = $stmt->fetchAll();
echo json_encode($results);
}
$conn = null;
Don't use same $k; use a variable and increment it with each bind; See below
$bindingIndex = 0;
if( !empty( $books_ids ))
{
foreach ($books_ids as $k => $id) {
$stmt->bindValue((++$bindingIndex), $id);
}
}
if( !empty( $authors_ids ))
{
foreach ($authors_ids as $k => $id) {
$stmt->bindValue((++$bindingIndex), $id);
}
}
if( !empty( $stores_ids ))
{
foreach ($stores_ids as $k => $id) {
$stmt->bindValue((++$bindingIndex), $id);
}
}

MySQLi prepared statement within while loop

I'm attempting to execute 4 prepared statement within a mysqli_fetch_row while loop. Currently my code is outputting NULL or empty values for all queries. This is my first time using prepared statements and I am trying to convert my code from mysql queries to mysqli. My code is below:
$users = mysqli_query($link, "SELECT id FROM users WHERE approved = '1'");
while ($user = mysqli_fetch_row($users)) {
if ($twitter_username_query = mysqli_prepare($username_query, "SELECT username FROM personas WHERE user_id = ?")) {
mysqli_stmt_bind_param($username_query, "d", $user[0]);
mysqli_stmt_execute($username_query);
mysqli_stmt_bind_result($username_query, $username);
mysqli_stmt_fetch($username_query);
mysqli_stmt_close($twitter_username_query);
}
if ($count_user_clicks = mysqli_prepare($count_user_clicks, "SELECT count(distinct txid) FROM users_clicks WHERE user_id = ?")) {
mysqli_stmt_bind_param($count_user_clicks, "d", $user[0]);
mysqli_stmt_execute($count_user_clicks);
mysqli_stmt_bind_result($count_user_clicks, $user_clicks);
mysqli_stmt_fetch($count_user_clicks);
mysqli_stmt_close($count_user_clicks);
}
if ($count_user_installs = mysqli_prepare("SELECT count(txid) FROM (SELECT txid FROM users_installs WHERE user_id = ? GROUP BY txid) table1")) {
mysqli_stmt_bind_param($count_user_installs, "d", $user[0]);
mysqli_stmt_execute($count_user_installs);
mysqli_stmt_bind_result($count_user_installs, $user_installs);
mysqli_stmt_fetch($count_user_installs);
mysqli_stmt_close($count_user_installs);
}
if ($calc_user_cost = mysqli_prepare($calc_user_cost, "SELECT sum(earnings) FROM (SELECT max(cost) as earnings FROM users_clicks WHERE user_id = ? GROUP BY txid) table1")) {
mysqli_stmt_bind_param($calc_user_cost, "d", $user[0]);
mysqli_stmt_execute($calc_user_cost);
mysqli_stmt_bind_result($calc_user_cost, $user_cost);
mysqli_stmt_fetch($calc_user_cost);
mysqli_stmt_close($calc_user_cost);
}
if ($user_clicks == '0') {
$user_conv = 0;
} else {
$user_conv = ($user_installs / $user_clicks) * 100;
}
echo "<tr>";
echo "<td><b>".$username."</b></td>";
echo "<td>".number_format($user_clicks)."</td>";
echo "<td>".number_format($user_installs)."</td>";
if ($user_installs[0] == '0') {
echo "<td>$0.00</td>";
} else {
echo "<td>$".number_format($user_cost / $user_installs, 2)."</td>";
}
echo "<td>".number_format($user_conv, 2)."%</td>";
echo "</tr>";
}
Use a single query that JOINs all the subqueries:
SELECT u.id, p.username, IFNULL(c.clicks, 0) AS clicks, IFNULL(i.installs, 0) AS installs, IFNULL(e.earnings, 0) AS earnings
FROM users AS u
JOIN personas AS p ON p.user_id = u.id
LEFT JOIN (
SELECT user_id, COUNT(DISTINCT txid) AS clicks
FROM user_clicks
GROUP BY user_id) AS c ON c.user_id = u.id
LEFT JOIN (
SELECT user_id, COUNT(DISTINCT txid) AS installs
FROM user_installs
GROUP BY user_id) AS i ON i.user_id = u.id
LEFT JOIN (
SELECT user_id, SUM(earnings) AS earnings
FROM (SELECT user_id, txid, MAX(cost) AS earnings
FROM user_clicks
GROUP BY use_id, txid) AS table1
GROUP BY user_id) AS e
WHERE u.approved = 1

Categories