I am trying to make a search script that searches cars in a database and matches ALL keywords input by user. If I leave keywords text box empty and search I get results but if I input any keywords I get no results.
$search_keywords = $_POST['search_keywords'];
$terms = $search_keywords;
$items = explode(' ',$terms);
$types = array();
foreach ($items as $item) {
$types[] = "'title' LIKE '%{$item}%'";
$types[] = "'exterior_colour' LIKE '%{$item}%'";
}
$sql = "SELECT * FROM list_car WHERE ";
$sql .= implode(" && ", $types) . " ORDER BY 'title'";
$result = mysqli_query($link, getPagingQuery($sql, $rowsPerPage));
UPDATE:
Works now i have changed it but if i search Toyota hilux dfkjodsgfudsugfdsgfgfgfdgfdg all the Toyota hilux will appear but dfkjodsgfudsugfdsgfgfgfdgfdg is garbage which is not listed in the database i want it to match ALL keywords not just one or more.
$search_keywords = $_POST['search_keywords'];
$terms = $search_keywords;
$items = explode(' ',$terms);
$types = array();
foreach ($items as $item) {
$types[] = "`title` LIKE '%{$item}%'";
$types[] = "`exterior_colour` LIKE '%{$item}%'";
}
$sql = "SELECT * FROM list_CAR WHERE ";
$sql .= implode(" || ", $types) . "";
$result = mysqli_query($link, getPagingQuery($sql, $rowsPerPage)) or die(mysqli_error($link));
You should use OR (||) instead of AND (&&) . As it is, your search term must match against all fields:
$sql = "SELECT * FROM list_car WHERE ";
$sql .= implode(" OR ", $types) . " ORDER BY 'title'";
Here's how I'd do it.
$terms = $search_keywords = 'Toyota hilux dfkjodsgfudsugfdsgfgfgfdgfdg';
$items = explode(' ',$terms);
$types = array();
$sql = "SELECT * FROM list_CAR WHERE ";
foreach ($items as $item) {
$sql .= " (`title` LIKE ? or `exterior_colour` LIKE ?) and ";
$params[] = '%' . $item . '%';
$params[] = '%' . $item . '%';
}
if(!empty($params)) {
$sql = rtrim($sql, ' and ');
$result = mysqli_prepare($link, $sql);
foreach($params as $param) {
mysqli_stmt_bind_param($result, "s", $param);
}
mysqli_stmt_execute($result);
} else {
die('No params built...WHY');
}
Note I'm using untested mysqli prepared statements, I haven't built the parameterized queries procedurally in mysqli, I base this approach off user comments on the manual's page.
This should give a query such as
SELECT * FROM list_CAR
WHERE
(`title` LIKE ? or `exterior_colour` LIKE ?) and
(`title` LIKE ? or `exterior_colour` LIKE ?) and
(`title` LIKE ? or `exterior_colour` LIKE ?)
Which will require each keyword is present in the title or the color list.
If you were to keep it unprepared, which is unrecommended and poor practice, it would be..
$terms = $search_keywords = 'Toyota hilux dfkjodsgfudsugfdsgfgfgfdgfdg';
$items = explode(' ',$terms);
$types = array();
foreach ($items as $item) {
$types[] = " (`title` LIKE '%{$item}%' or `exterior_colour` LIKE '%{$item}%') ";
}
$sql = "SELECT * FROM list_CAR WHERE ";
$sql .= implode(" and ", $types) . "";
echo $sql;
Output:
SELECT * FROM list_CAR WHERE
(`title` LIKE '%Toyota%' or `exterior_colour` LIKE '%Toyota%') and
(`title` LIKE '%hilux%' or `exterior_colour` LIKE '%hilux%') and
(`title` LIKE '%dfkjodsgfudsugfdsgfgfgfdgfdg%' or `exterior_colour` LIKE '%dfkjodsgfudsugfdsgfgfgfdgfdg%')
Related
I want to do a search in a table with search words defined by a user.
I'm doing this by splitting the string an constructing the sql.
But i can't seem to make it work. It works fine, if only one word is entered, but with two or more words it's crashing.
$q = $_GET['q']; //Search word
$q = htmlspecialchars($q);
$q_exploded = explode ( " ", $q );
foreach( $q_exploded as $search_each ) {
$where .= "content LIKE ? OR ";
$bind .= "s";
$param .= "%$search_each%, ";
}
$where = rtrim($where,'OR ');
$param = rtrim($param,', ');
$sql = "SELECT ads_id FROM search_index WHERE ".$where."";
echo $sql . "<br>".$param."<br>".$bind."<br>";
$stmt = $dbconn->prepare($sql);
$stmt->bind_param($bind, $param);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['ads_id'];
}
This is my error
SELECT ads_id FROM search_index WHERE content LIKE ? OR content LIKE ?
%word1%, %word2%
ss
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables
You issue is here:
$stmt->bind_param($bind, $param);
What you're doing is:
$stmt->bind_param("ss", $param);
While you may intend param to satisfy both of the strings it doesn't you need to pass a variable for each one. I would try looking into explode for this.
Someone posted an answer earlier, but deleted it again. That answer actually worked, i just needed to change from mySQLi to DPO.
Solution:
$q = htmlspecialchars($q);
$q_exploded = explode ( " ", $q );
$where = [];
$bind = [];
foreach ($q_exploded as $idx => $search_each) {
$key = ':val' . $idx;
$where[] = "content LIKE " . $key;
$bind[$key] = "%$search_each%";
}
$sql = "SELECT ads_id FROM search_index WHERE " . implode(" OR ", $where);
$stmt = $pdo_conn->prepare($sql);
$stmt->execute($bind);
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $stmt->fetch()) {
echo $row['ads_id'] . "<br>";
}
I am creating search query in php by passing variable through GET method. When the variable is null then it's passing the query like,
SELECT * FROM table WHERE column_name = null.
And it's showing error (obvious). I want to create query like. If user don't select anything from search options then it should fetch all the data from that column.
What's the correct logic for that?
Thanks.
Code:
if(isset($_GET['selPetType']) && $_GET['selPetType'] != '')
{
$searchParams['petType'] = $_GET['selPetType'];
$queryStr .= " PetType='" .$_GET['selPetType']. "'";
}
if(isset($_GET['txtPetBreed1']) && !empty($_GET['txtPetBreed1']))
{
$searchParams['breed'] = $_GET['txtPetBreed1'];
$queryStr .= " AND PetBreed1 ='". $_GET['txtPetBreed1'] . "'";
}
$clause1 = "SELECT * FROM pet WHERE $queryStr ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit";
$totalRun1 = $allQuery->run($clause1);
Maybe something like this:
$get['param1'] = 'foo';
$get['param3'] = null;
$get['param2'] = '';
$get['param4'] = 'bar';
$where = null;
foreach ($get as $col => $val) {
if (!empty($val)) {
$where[] = $col . ' = "' . $val . '"';
}
}
$select = 'SELECT * FROM pet ';
if ($where) {
$select .= 'WHERE ' . implode(' AND ', $where);
}
$select .= ' ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit';
Edit: I added if to remove empty values and added 2 new values to example so you can see this values will not be in query.
if(isset($_GET['your_variable'])){
$whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}
$qry ="SELECT * FROM table WHERE ".$whr;
For example :
<?php
$userSelectedValue = ...;
$whereCondition = $userSelectedValue ? " AND column_name = " . $userSelectedValue : "" ;
$query = "SELECT * FROM table WHERE 1" . $whereCondition;
?>
Then consider it's more safe to use prepared statements.
I would like to add " AND " in between the key and value pair arguments for my sql query but I don't know how. I have tried search the net but unable to find a solution.
$cdatahome = fetchCategory(array("status"=>"1","home"=>"1"));
function fetchCategory(array $conditions){
$db = Core::getInstance();
$sql = "SELECT id, title FROM ruj_category WHERE ";
$params = array();
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
$sql .= "$column = ?";
$params[] = $value;
}
}
$sql .= " order by title asc";
$res = $db->dbh->prepare($sql);
$res->execute(array_values($params));
$res = $res->fetchAll(PDO::FETCH_ASSOC);
return $res;
$where = array();
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
$where[] = "$column = ?";
$params[] = $value;
}
}
$sql .= implode(' AND ', $where);
$cdatahome = fetchCategory(array("status"=>"1","home"=>"1"));
function fetchCategory(array $conditions){
$db = Core::getInstance();
$sql = "SELECT id, title FROM ruj_category WHERE ";
$params = array();
$i = 0;
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
if($i != 0){
$sql .= ' AND ';
}
$sql .= "$column = ?";
$params[] = $value;
$i++;
}
}
$sql .= " order by title asc";
$res = $db->dbh->prepare($sql);
$res->execute(array_values($params));
$res = $res->fetchAll(PDO::FETCH_ASSOC);
return $res;
Usually, when I want to put something like AND or & (in the case of URLs), I create an array and implode it on the string I want in the middle. For example:
$items = array("a", "b", "c");
$output = implode(" AND ", $items);
Outputs:
"a AND b AND c"
In your case, you can do your foreach loop to build the string pieces and then use AND as glue in the implode() function as listed out by the second answer.
First, you could put the conditions into an array, as you do with the values to $params. Like $cond[]="$column = ?" and then $sql.=implode(' AND ',$cond);
To have it solved in your foreach: before the loop set $first=false; and in the loop do $sql.=($first?'':' AND ')."$column = ?"; $first=false;
hi all Im trying to create a php search page that will bring up a list of books from a mysql database, then when the book name is clicked bring up a a list of books that are in a relationship table with them. I'm slightly struggling with the code and was hoping someone would be able to lend a hand
-This is my search.php file
<?php
$i=0;
$column_name = 'title'; // column to search by
$k =$_GET['k'];
$terms = explode(" ",$k);
//connect before calling mysql_real_escape_string
mysql_connect("localhost","","");
mysql_select_db("test");
$query ="SELECT id,title,author
FROM books WHERE";
foreach ($terms as $each){
$i++;
$each = '%' . $each . '%'; // add wildcard
$each = mysql_real_escape_string($each); // prevent sql injection
if($i==1)
$query .= " $column_name LIKE '$each' ";
else
$query .= " OR $column_name LIKE '$each' ";
}
echo 'QUERY: ' . $query;
$query = mysql_query($query) OR DIE(mysql_error());
//Code below is for using the relationships table assuming you have a column name id that
//references to the relationships table. Also, you should add a index on the column id.
$results = "";
while($row = mysql_fetch_array($query)) {
$results .= '<li>
'.$row['title'].' author: '.$row['author'].'
</li>';
}
$results = '<ul>' . $results . '</ul>';
echo $results;
Remove a "; from this line:
FROM books WHERE "; ";
You must declare $i
$i = 0;
To prevent sql injection you can use:
foreach ($terms as $each){
$i++;
$each = '%' . $each . '%'; // add wildcard
$each = mysql_real_escape_string($each); // prevent sql injection
if($i==1)
$query .= " $keywords LIKE '$each' ";
else
$query .= " OR $keywords LIKE '$each' ";
}
Also, ake sure the user cannot set the variable to a table that does not exist
Full Code
<?php
$i=0;
$column_name = 'title'; // column to search by
$k =$_GET['k'];
$terms = explode(" ",$k);
//connect before calling mysql_real_escape_string
mysql_connect("localhost","","");
mysql_select_db("test");
$query ="SELECT id,title,author
FROM books WHERE";
foreach ($terms as $each){
$i++;
$each = '%' . $each . '%'; // add wildcard
$each = mysql_real_escape_string($each); // prevent sql injection
if($i==1)
$query .= " $column_name LIKE '$each' ";
else
$query .= " OR $column_name LIKE '$each' ";
}
echo 'QUERY: ' . $query;
$query = mysql_query($query) OR DIE(mysql_error());
//Code below is for using the relationships table assuming you have a column name id that
//references to the relationships table. Also, you should add a index on the column id.
$results = "";
while($row = mysql_fetch_array($query)) {
$results .= '<li>
'.$row['title'].' author: '.$row['author'].'
</li>';
}
$results = '<ul>' . $ results . '</ul>';
echo $results;
I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.