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."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
i need to do multiple search, with first_name,last_name,middle_name,contact_no1 fields
If you want to do search with all fields add fields in WHERE with OR:
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword OR last_name LIKE :keyword OR middle_name LIKE :keyword OR contact_no1 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);
}
public function search($requestArray){
$sql = "";
if( isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE AND (`first_name` LIKE '%".$requestArray['search']."%' OR `last_name` LIKE '%".$requestArray['search']."%')";
if(isset($requestArray['firstname']) && !isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `first_name` LIKE '%".$requestArray['search']."%'";
if(!isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `last_name` LIKE '%".$requestArray['search']."%'";
$STH = $this->DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_OBJ);
$someData = $STH->fetchAll();
return $someData;
}
I used this method in one of my project for searching with two field hope it could help you. where $requestArray will get the data from form and 'firstname' , 'lastname' are two key of the array which you will enter your searchbox and submit to search. I just showed you here the query style and before that you have tor trim the values.
Related
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 figure out how can I build a query in PDO like this one
//...
$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = '1'";
if($this->is($_GET, 'category')) {
$sql['category'] = "AND `category` = '".$_GET['category']."'";
}
if($this->is($_GET, 'tags')) {
$sql['tags'] = "AND `tags` LIKE '%".$_GET['tags']."%'";
}
$sql[] = "ORDER BY `id` DESC LIMIT ".$offset.", ".$rows_per_page;
$query = $this->query(implode(" ", $sql));
//...
I tried something like that..
$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = :completed";
if($this->is($_GET, 'category')) {
$sql['category'] = "AND `category` = :category";
}
$sql[] = "LIMIT 0, 5";
$this->db->query(implode(" ", $sql));
$this->db->bind(array(
':completed' => 1,
':category' => $this->is($_GET, 'category')
));
$fetch = $this->db->fetchAll();
print_r($fetch);
but there's a error that says I can not bind nonexistent variables "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens"
...and with some research I figure out I can not bind before query
..so.. do you have any idea how can I do this?
$name1 = #$_GET['search'] ;
$name = split(" +",$name1);
$query = "select * from table where field1 = '".$name[0]."'
and field2 = '".$name[1]."'
Order By `date` DESC";
I make a easy search like that, but if $name[0] and $name[1] all have data, the query can work, and if $name[1] is empty, the query is failed. how to add a judge that if $name[1] is empty, hidden and field2 = '".$name[1]."', and make the query like
$query = "select * from table where field1 = '".$name[0]."' Order BydateDESC";
You can do it with an or:
(and field2 = '".$name[1]."' or '".$name[1]."' = '')
Try this
if(!empty($name[0]) or !empty($name[1])){
$sql = "select * from table where ";
if($name[0]){
$fld1 = " field1 = '".$name[0]."'";
}
if($name[1]){
$fld2 = " field2 = '".$name[1]."'";
}
if($fld1 && $fld2)
{
$sql .= $fld1 ." and ".$fld2;
}
elseif($fld1){
$sql .= $fld1;
}
elseif($fld2){
$sql .= $fld2;
}
}
It will be better if you in your PHP script, do this check like this
$query = "select * from table where field1 = '$name[0]'"
if ($name[1]) $query .= " and field2 = '$name[1]'";
$query .= 'order by date desc';
$name[1]?'query of it exists':'query if it doesn't';
I'm having a little trouble getting this query to work:
$userId = mysql_real_escape_string( $_SESSION['user_id'] );
$userPassProvided = mysql_real_escape_string( $_POST['oldPassword'] );
$query = "SELECT user_id, AES_DECRYPT( user_pass, '".$db_aes_key."' ) AS user_pass ";
$query .= "FROM users_tbl WHERE MATCH( user_id, user_pass ) ";
$query .= "AGAINST( '".$userId."', '".$userPassProvided."' IN BOOLEAN MODE ) LIMIT 1";
$result = mysql_query( $query, $mysql_db );
What I would like to do is query users_tbl for the record wherein user_id and user_pass are the same as $userId and $userPassProvided, respectively. Can someone please tell me what is wrong with my query?
Thanks. :)
The following is functionally equivalent to what you seem to want to do. (Do read "however..." below)
$query = "SELECT user_id, AES_DECRYPT( user_pass, '".$db_aes_key."' ) AS user_pass ";
$query .= "FROM users_tbl ";
$query .= "WHERE user_id = '".$userId."' ";
$query .= " AND AES_DECRYPT(user_pass, '".$db_aes_key."' ) = '".$userPassProvided."' ";
$query .= "LIMIT 1";
...however MySQL would have to AES-decript every single encoded password in the database. This will be both computationally expensive and prevent using any SQL index.
Alternatively, you may consider encrypting the supplied password, and match it to the ones stored in the database. Maybe something like that (note: untested):
$query = "SELECT user_id, AES_DECRYPT( user_pass, '".$db_aes_key."' ) AS user_pass ";
$query .= "FROM users_tbl ";
$query .= "WHERE user_id = '".$userId."' ";
$query .= " AND user_pass = AES_ENCRYPT('".$userPassProvided."', '".$db_aes_key."' ) ";
$query .= "LIMIT 1";
MATCH () AGAINST () doesn't work like you're expecting it to. What it does is attempts to match a single string in AGAINST() against each of the columns provided in MATCH(), rather than comparing value1 against column1 and value2 against column2.
Have you tried ...WHERE user_id = '".$userId."' AND user_pass = '"$userPassProvided"' LIMIT 1?