Multiple IN operator mysql combine - php

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) )
)
...

Related

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);
}
});

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);
}
}

adding a where variable inside sql

if user select anything besides "all" it will lead to a where statement involving KodDaerah
$where = '';
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".mysql_real_escape_string($where)."
ORDER BY koddaerah.NamaDaerah ";
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
if user select all then the system will just use the current sql statement that i provided, for now im not sure what's wrong, so here is where user select the KodDaerah from drop down list box
<?php include('dbase.php');
$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required />
<option>Pilih Daerah</option>
<option value='all'>Seluruh Pahang</option>";
while ($kod = mysql_fetch_array ($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</option>
<option value='all'>Seluruh Pahang</option>";
}
echo "<?select>";
?>
The problem is now even when i select a certain KodDaerah, it will just run the provided sql query without using the WHERE statement in the $where. Can anybody help?
EDIT:
$sql = $sql . $where;
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);
try to move up the if statement:, remove mysql_real_escape_string
(escape before)
$where = '';
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".$where."
ORDER BY koddaerah.NamaDaerah ";
and then do not append $where again
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);

Using one UPDATE query for more than a single row/ colum

How would I go about putting my code into one UPDATE statement, bearing in mind that i'm doing a lot of conditional statements:
$updateTbl1 = "UPDATE $tableNameOrig o, $tableNameTemp t SET o.customerAge = t.customerAge WHERE o.id = t.id AND (o.customerAge != t.customerAge );";
$updateTbl2 = "UPDATE $tableNameOrig o, $tableNameTemp t SET o.customerCode = t.customerCode WHERE o.id = t.id AND (o.customerCode != t.customerCode);";
$updateTbl3 = "UPDATE $tableNameOrig o, $tableNameTemp t SET o.customerName = t.customerName WHERE o.id = t.id AND (o.customerName != t.customerName);";
$updateTbl4 = "UPDATE $tableNameOrig o, $tableNameTemp t SET o.customerEmail = t.customerEmail WHERE o.id = t.id AND (o.customerEmail != t.customerEmail);";
$updateTbl5 = "UPDATE $tableNameOrig o, $tableNameTemp t SET o.customerAddress = t.customerAddress WHERE o.id = t.id AND (o.customerAddress != t.customerAddress);";
$updateTbl6 = "UPDATE $tableNameOrig o, $tableNameTemp t SET o.customerAdded = t.customerAdded WHERE o.id = t.id AND (o.customerAdded != t.customerAdded);";
(mysqli_query($con,$updateTbl1));
(mysqli_query($con,$updateTbl2));
(mysqli_query($con,$updateTbl3));
(mysqli_query($con,$updateTbl4));
(mysqli_query($con,$updateTbl5));
(mysqli_query($con,$updateTbl6));
Thanks!
UPDATE $tableNameOrig o
JOIN $tableNameTemp t
ON o.id = t.id
SET o.customerAge = t.customerAge,
o.customerCode = t.customerCode,
o.customerName = t.customerName,
o.customerEmail = t.customerEmail,
o.customerAddress = t.customerAddress,
o.customerAdded = t.customerAdded
Your other conditions are meaningless.

PHP & MySQL totalrow counting with condition

I have a problem to get total rows counting with condition. This is my code
$pagesize = 10;
$recordstart = (int)$_GET['recordstart'];
$recordstart = (isset($_GET['recordstart'])) ? $recordstart : 0;
$town = $_GET['label_town'];
$sub = ucfirst($_GET['label_sub']);
Here is my selecting condition. I also use this condition to count totalrows
if (isset($_GET['label_town']) === true && isset($_GET['label_sub']) === true) {
$where = "WHERE p.label_town = '$town' AND p.label_sub = '$sub' AND `visible` = 1";
} else if (isset($_GET['label_town']) === true && isset($_GET['label_sub']) === false) {
$where = "WHERE p.label_town = '$town' AND `visible` = 1";
} else {
$where = "WHERE `visible` = 1";
}
// Selecting data
$all_page_index = mysql_query("SELECT p.page_id, p.timestamp, p.label_town, p.label_sub, p.ime_nekretnine, p.mjesto, p.cijena_noc, p.krevet_apart, p.broj_apart, p.min_nocenja, p.description, p.visits, i.image_id, i.page_id, i.ext
FROM data_page AS p
LEFT JOIN (
SELECT MAX( image_id ) AS max, page_id
FROM images
GROUP BY page_id
) AS n ON p.page_id = n.page_id
LEFT JOIN images AS i ON i.image_id = n.max
$where
ORDER BY p.page_id DESC
LIMIT $recordstart, $pagesize");
// Counting rows with conditions
function totalrows() {
return mysql_result(mysql_query("SELECT COUNT(p.page_id) FROM data_page AS p $where"), 0);
}
Selecting and displaying data works fine but problem is with SELECT COUNT. Always count totalrows no mater what condition is. Where I making wrong?
Thanks!
Your COUNT is within function definition, where $where isn't defined. You need to pass it as a parameter or move query outside the function.

Categories