Pagination works fine when I don't use the WHERE statement in my SELECT statement. For some reason as soon as I add additional requests in the SELECT statement, only the 1st pagination page works. So it seems like the variable data is lost after the first page is displayed. Below is some of the code:-
<?php
include 'database.php';
include 'paginator.php';
$pdo = Database::connect();
$paginator = new Paginator();
$sql = "SELECT count(*) FROM customer_crm ";
$paginator->paginate($pdo->query($sql)->fetchColumn());
$query = $_GET["query"];
if (isset($query)) {
($_GET['query'])?('%'.$_GET['query'].'%'):'%';
$sql = "SELECT * FROM customer_crm WHERE firstname LIKE :query OR email LIKE :query OR telephone LIKE :query ";
}
else {
$start = (($paginator->getCurrentPage()-1)*$paginator->itemsPerPage);
$length = ($paginator->itemsPerPage);
//$sql = "SELECT * FROM customer_crm WHERE customer_group_id = $input OR date_followup= CURDATE() ORDER BY customer_group_id DESC limit $start, $length ";
$sql = "SELECT * FROM customer_crm ORDER BY date_followup DESC limit $start, $length ";
//$sql = "SELECT * FROM customer_crm WHERE customer_group_id = $input ORDER BY date_followup DESC limit $start, $length ";
}
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
Without knowing which Paginator are we talking about, I could only advise you to do something like
include 'database.php';
include 'paginator.php';
$pdo = Database::connect();
$paginator = new Paginator();
$query = (isset($_GET["query"]) && strlen($_GET["query"])>1)? '%'.$_GET["query"].'%':'%';
$countsql = "SELECT * FROM customer_crm WHERE firstname LIKE :query OR email LIKE :query OR telephone LIKE :query ";
$sthcount = $pdo->prepare($countsql);
$sthcount->bindParam(':query',$query,PDO::PARAM_STR);
$sthcount->execute();
$count=$sthcount->fetchColumn();
$paginator->paginate($count);
$start = (($paginator->getCurrentPage()-1)*$paginator->itemsPerPage);
$length = ($paginator->itemsPerPage);
$sql = $countsql . ' ORDER BY date_followup DESC limit :start, :length ';
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
See, you where making two mistakes here:
getting your count value without considering the query. You should set the value of $query regardless of the existance of $_GET['query'], and use it in your count query as well as your results query.
binding parameters whose placeholders and values do not exist in the query you're executing. Make sure your results query contains :query, :start and :length or you will be binding more parameters than the query has.
You should also have wrapped your statements in try/catch blocks so you could debug what was happening.
try {
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
} catch(\PDOException $e) {
die('Error in query: '. $e->getMessage());
}
That way you would have known that the query was failing because of
Invalid parameter number: parameter was not defined
NOTE I have no clue about how your paginator will know about the current page, nor can I see where are you setting the itemsPerPage value.
Related
The following is the PHP code I am using for a simple search feature in my website.
The search simply shows refults if it matches the SQL column "tags".
I would like to add one more filter in the SQL query.
I want to filter the search results based on city.
The city data is already in the SQL, but I dont know how to add it here without breaking the properly working search funtion.
I tried $data_sql .= " AND city='newyork' "; after the 8th line, but it didnt work.
$name=str_replace(' ', '%', $_POST['query']);
$newsearch = "%$name%";
$base_sql = "SELECT %s FROM posts WHERE tags LIKE ?";
$count_sql = sprintf($base_sql, "count(*)");
$stmt = $connect->prepare($count_sql);
$stmt->execute([$newsearch]);
$total_data = $stmt->fetchColumn();
$data_sql = $count_sql = sprintf($base_sql, "*")." LIMIT ?,?";
$stmt = $connect->prepare($data_sql);
$stmt->execute([$newsearch, $start, $limit]);
$result = $stmt->fetchAll();
So your additional filter must be before LIMIT ?, ?
if you try adding it after the 8th line the query will look like this:
SELECT * FROM posts WHERE tags LIKE 'search' LIMIT 0, 100 AND city='newyork'
so what can you do:
$data_sql = sprintf($base_sql, "*");//we will add the limit before preparation
//don't know why do you need that $count_sql here
$data_sql .= " AND city='newyork' ";
//IF you need some GROUP BY do it here
//If you need some ORDER BY do it here
$data_sql .= " LIMIT ?, ?";
$stmt = $connect->prepare($data_sql);
$stmt->execute([$newsearch, $start, $limit]);
$result = $stmt->fetchAll();
The line $data_sql .= " AND city='newyork' "; won't work as it will add the string after the LIMIT which is not a valid sql query.
You should instead edit the line with the base_sql like this:
$base_sql = "SELECT %s FROM posts WHERE tags LIKE ? AND city='newyork'";
And of course if 'newyork' needs to be a variable you can do thr same thing like you did for the tags
First, let's add the new criteria:
$base_sql = "SELECT %s FROM posts WHERE tags LIKE ? and city = ?";
Then make sure that you pass the city as a parameter
$stmt->execute([$newsearch, 'newyork', $start, $limit]);
I have a SQL query that is based on user input.
However, in the table, theres a "-1" at the end of every word that you search for.
For example if you want to get the sql result of car, it's actually named car-1 in the database, but the user should only be able to search for car.
This is how its setup:
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query);
$stmt->execute();
$result = $stmt->get_result();
What I want, is that the select query should be like:
$sql = "SELECT * FROM that WHERE this = ? + '-1'";
But ^^ doesn't work.
$sql = "SELECT * FROM test WHERE NAME='car' & -1";
test = that
NAME= table name
'car' = this
Why don't you just concat -1 to search_query :
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query.'-1');
$stmt->execute();
$result = $stmt->get_result();
Using MySQL:
$sql = "SELECT * FROM that WHERE this = CONCAT(?, '-1')";
Using PHP:
$stmt->bind_param('s', $search_query . "-1");
I need to create a Prepared statement and incorporate it into a SELECT statement, as shown below. I am happy with creating the Prepared statement for line 1, but I need to include the result in the SELECT statement in line 2 as I cannot use the WHERE option because of line 4 (function of a search)
So, I guess I need some insight into how I can combine both the SELECT and prepared statement into line 2.
//$sql = "SELECT * FROM customer_crm WHERE sales_agent = '".$username."'";
$sql = "SELECT * FROM customer_crm";
$query = isset($_GET['query'])?('%'.$_GET['query'].'%'):'%';
$sql .= "WHERE company_name LIKE :query OR email LIKE :query OR
date_followup LIKE :query "; //is needed for a search function
$start = (($paginator->getCurrentPage()-1)*$paginator->itemsPerPage);
$length = ($paginator->itemsPerPage);
$sql .= "ORDER BY date_followup DESC limit :start, :length ";
$sth = $pdo->prepare($sql);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row1)
You can't have two WHERE clauses. The second one should be AND to combine those conditions into the query.
$sql = "SELECT * FROM customer_crm WHERE sales_agent = :username";
$query = isset($_GET['query'])?('%'.$_GET['query'].'%'):'%';
$sql .= " AND (company_name LIKE :query OR email LIKE :query OR
date_followup LIKE :query)"; //is needed for a search function
$start = (($paginator->getCurrentPage()-1)*$paginator->itemsPerPage);
$length = ($paginator->itemsPerPage);
$sql .= " ORDER BY date_followup DESC limit :start, :length ";
$sth = $pdo->prepare($sql);
$sth->bindParam(':username', $username, PDO::PARAM_STR);
$sth->bindParam(':start',$start,PDO::PARAM_INT);
$sth->bindParam(':length',$length,PDO::PARAM_INT);
$sth->bindParam(':query',$query,PDO::PARAM_STR);
$sth->execute();
When I execute this query to the DB:
SELECT * FROM `task` WHERE `date_time_from` like '%0000%'
I get a few results, now I am trying to do the same with PDO and I can not manage to get any results or errors. This is what I have done:
$dbChain = 'mysql:host='.$GLOBALS['dbhost'].';dbname='.$GLOBALS['dbname'];
try{
$dbh = new PDO($dbChain, $GLOBALS['dbuser'], $GLOBALS['dbpassword']);
$sql = "SELECT * FROM task"
. "WHERE date_time_from like CONCAT('%', :dateFrom, '%')";
$a = '0000';
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':dateFrom', $a);
$stmt->execute();
$total = $stmt->rowCount();
echo $total;
while ($row = $stmt->fetch()){
var_dump($row);
}
} catch (Exception $e){
echo 'Error'.$e->getMessage();
}
The result of this is $total = 0. Can anyone tell me what am I doing wrong?
I have also tried this:
$sql = "SELECT * FROM task"
. "WHERE date_time_from like :dateFrom";
$a = "%0000%";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':dateFrom', $a);
$stmt->execute();
Same result for $total.
bindParam escapes the "%" in the query. It will not work as you expect...
You can, however, use bindValue like so...
$sql = "SELECT * FROM task WHERE date_time_from LIKE ?";
$stmt = $dbh->prepare($sql);
$stmt->bindValue( 1, "%0000%" );
$stmt->execute();
Alternatively, if you want 0 values from a datetime column, you can just do this:
$sql = "SELECT * FROM task WHERE date_time_from = '0000-00-00'";
I'm trying to run an alternate query if the initial query fails (it does because the id I'm searching for in this instance only exists in one of the databases being joined) using an if statement and I've constructed it like so:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/php/link_costreport_2013.php');
$id = $_GET['id']; //ID # For page/query
if($query = $link->prepare("SELECT locale.id, locale.provider_num, locale.provider_name, locale.state, locale.city,
finstat_ca.coh_and_banks, finstat_ca.temp_investments, finstat_ca.notes_receivable, finstat_ca.accounts_receivable, finstat_ca.other_receivables,
finstat_ca.afun_and_ar, finstat_ca.inventory, finstat_ca.prepaid_expenses, (finstat_ca.other_cur_assets + finstat_ca.due_from_other_funds) as other_cur_assets, finstat_ca.total_current_assets,
finstat_fa.total_fixed_assets,
finstat_olta.investments, (finstat_olta.dep_on_leases + finstat_olta.due_from_owners_officers + finstat_olta.other_assets) as all_olta, finstat_olta.total_other_assets, finstat_olta.end_assets,
finstat_cl.accounts_payable, finstat_cl.salaries_wages_fees_payable, finstat_cl.payroll_taxes_payable, finstat_cl.notes_loans_payable, finstat_cl.deferred_income, finstat_cl.total_current_liabilities,
(finstat_cl.total_current_liabilities - (finstat_cl.accounts_payable + finstat_cl.salaries_wages_fees_payable + finstat_cl.payroll_taxes_payable + finstat_cl.notes_loans_payable + finstat_cl.deferred_income)) as all_other_cl,
finstat_ltl.mortgage_payable, finstat_ltl.notes_payable, finstat_ltl.unsecured_loans, finstat_ltl.other_long_term_liabilities, finstat_ltl.total_long_term_liabilities,
finstat_talfb.total_fund_balance, finstat_talfb.total_lia_plus_fb
FROM `locale`
INNER JOIN `finstat_ca`
ON locale.id = finstat_ca.id
INNER JOIN `finstat_fa`
ON locale.id = finstat_fa.id
INNER JOIN `finstat_olta`
ON locale.id = finstat_olta.id
INNER JOIN `finstat_cl`
ON locale.id = finstat_cl.id
INNER JOIN `finstat_ltl`
ON locale.id = finstat_ltl.id
INNER JOIN `finstat_talfb`
ON locale.id = finstat_talfb.id
WHERE locale.id = :id
LIMIT 1")){
} else {
$query = $link->prepare("SELECT id, provider_num, provider_name, state, city
FROM `locale`
WHERE id = :id
LIMIT 1");
}
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
echo json_encode($results);
Basically it defaults to the single table where the ID does exist and only pulls a couple fields as opposed to the large statement above it. My only issue is that my code here is not working. My JSON only says false when I echo it. It obviously should not.
Is there an error in my code here?
Thanks in advance
:edit: I should note that when I enter an ID that exists in all the tables joined, the correct result (json) is displayed on the page.
I believe the problem is that even if ID does not exist in the first query, the $query variable still has a proper query in it and there is nothing false about it. That's not what you should be if-testing.
I think you should be testing $results.
This shows you the logic.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql_1 = "SQL CODE FOR QUERY 1";
$sql_2 = "SQL CODE FOR QUERY 2";
$query = $link->prepare($sql_1);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if (!$results)
{
$query = $link->prepare($sql_2);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
}
echo json_encode($results);
However as you can see there are a few lines of code that are repeated inside the if-statement that very similar to code that was just before the if-statement. Perhaps with a loop that loops twice but breaks out if $results is not false would be neater.
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/php/link_costreport_2013.php');
//ID # For page/query
$id = $_GET['id'];
$sql[] = "SQL CODE FOR QUERY 1";
$sql[] = "SQL CODE FOR QUERY 2";
foreach ($sql as $sql_query)
{
$query = $link->prepare($sql_query);
$query->bindParam(':id', $id);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
if ($results)
{
break;
}
}
echo json_encode($results);
The world is your oyster.