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();
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");
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.
I have a code, in which there are users will search for the name from MySQL.
First the mysql should search in first_name, then go to last_name for the same search option and then display results. (From both First_name and Last_name)
I tried but it showed me only the results from first name
Please help me.
Here is the code:-
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} elseif ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (last_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
}else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
$stmt->execute();
$total_count = count($stmt->fetchAll());
Try to avoid posting same question in other ways, edit the same question.
You asked the same question in MYSQL OR not working
Hope this will really help you:-
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword OR last_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
}else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
$stmt->execute();
$total_count = count($stmt->fetchAll());
I have also answered your new repeated question https://stackoverflow.com/a/44859408/7678788
I'm trying to say if all the 'OR's match then display. If it's remotely close to the custodian then display (LIKE)
To Leo, Yes I tried :custodian heres whole code. I commented out what you suggested because that's what works for now. (also changed the sql). I'm curious if the first query where I'm trying to get the 'count' matters. Let me know. Thanks.
$q = $_GET['q'];
$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets WHERE po = :query OR serialNum = :query OR dop = :query OR purchaseFrom = :query OR custodian = :query");
$STH->bindParam(':query', $q);
//$STH->bindParam(':custodian', '%'.$q.'%');
$STH->execute();
if ($STH->fetchColumn() > 0) {
$STH = NULL;
$STH = $dbh->prepare("SELECT * FROM inv_assets WHERE po = :query OR serialNum = :query OR dop =:query OR purchaseFrom = :query OR custodian = :query");
$STH->bindParam(':query', $q);
//$STH->bindParam(':custodian', '%'.$q.'%');
$STH->execute();
showTable($STH,$perms);
LIKE replaces = not OR
Example:
SELECT first_name, last_name
FROM student_details
WHERE first_name LIKE 'S%' OR last_name LIKE 'A%';
Take a look here: SQL Comparison Keywords
An example of how to do PDO LIKE Queries.
$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets
WHERE po = :query OR serialNum = :query OR dop = :query
OR purchaseFrom = :query OR custodian LIKE :custodian");
$ret = $STH->execute(array(':custodian' => '%'.$query.'%',':query' => $query));
Example with bindParam:
<?php
$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets
WHERE po = :query OR serialNum = :query OR dop = :query
OR purchaseFrom = :query OR custodian LIKE :custodian");
$STH->bindParam(':custodian', '%'.$q.'%');
$STH->bindParam(':query', $q);
$STH->execute();
?>
<?php
$STH = $dbh->prepare("SELECT COUNT(*) FROM inv_assets
WHERE po = :query OR serialNum = :query OR dop = :query
OR purchaseFrom = :query OR custodian LIKE :custodian");
$custodian = "%".$q."%";
$STH->bindParam(':custodian', $custodian);
$STH->bindParam(':query', $q);
$STH->execute();
?>
this will avoid passing parameter 2 by reference error and works