I am trying to write a simple search function that reads in a string $query.
my question is, can I use multiple ORs in a select statement? I am trying to search one string to see if it matches many column values, then print those rows.
function search($query) {
try {
$db = db_open();
$sql = "select * from pms where (name like :query) or (state like :query) or
(start like :query) or (finish like :query) ";
$statement = $db->prepare($sql);
$statement->bindValue(':query', $query);
$statement->execute();
$pms = $statement->fetchAll();
} catch(PDOException $e) {
die("Error: ".$e->getMessage());
}
return $pms;
}
This is not working, except when i search for a state.
Thanks
For sure.
SELECT * FROM pms WHERE (name LIKE :query) OR (start LIKE :query) OR (finish LIKE :query)
Should work just fine.
1) use backtick in table nam eand column names.
2) use bracket for each or for more clear understanding
3)if you are not using binding then use wildcat (%) with quotes .
try like this:
$sql = "select * from `pms`
where (`name` like '%query%')
OR (`state` like '%query%')
OR (`start` like '%query%')
OR (`finish` like '%query%') ";
Related
code:
<?php
include('config.php');
$return_arr = array();
$term = $_GET['term'];
$term = str_replace('.','',$term);
$sql = "SELECT * FROM submission where keyword like '%".$term."%' or companyname like '%".$term."%' ORDER BY CASE WHEN keyword LIKE '%".$term."%' THEN 1
ELSE 2 END";
$r = mysqli_query($link,$sql);
while($row = mysqli_fetch_assoc($r))
{
$key = explode(",", $row['keyword']);
foreach ($key as $keyword)
{
$return_arr[] = $keyword;
}
}
echo json_encode($return_arr);
?>
In my code I have created a auto complete suggestion box and its working but it always showing wrong result if I write (i) it always show result with (a) alphabet why not (i) and also want to search with short name. So, How can I do this ?Please help me.
Thank You
if you want to compare result start with input character then remove % from beginning
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";
You used %$term% in your query. So whether the data store the searched keyword anywhere in the string, it will display to you. So if you want to search the data start with a specific character remove % from the start of your query to make it as $term% as
$sql = "SELECT * FROM submission where keyword like '".$term."%' or companyname
like '".$term."%' ORDER BY CASE WHEN keyword LIKE '".$term."%' THEN 1
ELSE 2 END";
This is my code :
if(isset($_GET['search'])) {
$search_value= $_GET['searchbox'];
echo "Search results for $search_value";
print "<br><br>";
$query="
SELECT idemp,sn
FROM employee
WHERE idemp like '%search_value%'
OR sn like '%search_value%'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc($query)) {
$idemp=$row->idemp;
$sn=$row->sn;
echo $row['$idemp'];
echo $row['$sn'];
}
}
};
it didn't return matching result even if there is an equivalent in the database... help tnx...
Your'e not including the variable in the query, you're including only its name (without the $?).
$query="SELECT idemp,sn FROM employee
WHERE idemp like '%$search_value%' OR
sn like '%$search_value%'";
Since you're using mysqli, it would be better to bind the values either way, since it will normalize the input and prevent injection. Here's an example:
$conn->prepare("SELECT idemp,sn FROM employee
WHERE idemp like ? OR
sn like ?");
$conn->bind_params('ss', $search_value, $search_value);
$conn->execute(); // <-- returns the query results
Solved: Not sure why, but after I reloaded LAMP stack everything started to work just fine. Thank all of you for help!
I have following MySQL statement prepared in PHP:
SELECT * FROM my_table WHERE (country LIKE 'Latvia' AND phone NOT LIKE '371%')
which selects records with incorrect country phone codes.
In php it looks like this:
$sql = "SELECT * FROM {$table_name} WHERE (
country LIKE '$country' AND phone NOT LIKE '$phone_code%')";
While it perfectly filters records in phpMyAdmin, it doesn't works in my application - I get all of the records in including correct ones. Your help is really appreciated!
EDIT:
Here's how more code looks like:
while ($row = $this->fetch_array($result_set)) {
$countries_to_check[$row['short_name']] = $row['calling_code'];
}
$i = 1;
$sql = "SELECT * FROM {$this->table_name} WHERE ";
foreach ($countries_to_check as $country => $phone_code) {
if ($i > 1) {
$sql .= " OR ";
}
$sql .= "(country LIKE '".$country."' AND phone NOT LIKE '".$phone_code."%')";
$i++;
}
$result_set = $this->query($sql);
As I wrote in comments, all the variables are not empty, I have echoed $sql and even ran this query in phpMyAdmin, with success.
Result looks like this:
country phone
Lithuania 37028694529 * Correct
Latvia 37122171755 * Correct
Latvia 37522433153 * Incorrect
Latvia +37126378238 * Incorrect
Or with curly syntax
$sql = "SELECT * FROM {$table_name} WHERE (
country LIKE '{$country}' AND phone NOT LIKE '{$phone_code}%')";
It must be this way:
$sql = "SELECT * FROM {$table_name} WHERE (
country LIKE '".$country."' AND phone NOT LIKE '".$phone_code."%')";
I have this query
$DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
I need it to do so that the scrip dies if it gets a result, right now i have this :
if($DB->record_count() != 0) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
if($DB->record_count() != 0) {
Should this be something els? Because it dosnt die, even though i KNOW its got a result
This query looks like this in the phpscript. Its part of a bigger site
$DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
if($DB->record_count() != 0) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
$Properties['Title'] = String from the upload script that contains the titel.
$DB is the call til mysql
filter = the row in mysql
tfilter = the database name
WHAT DO I NEED:
I need the php to search the the tabel TFILTER in the row FILTER for matches to $Properties['Title'] and if it finds any then DIE. If the string: The.White.Tiger. exist in FILTER row, og the $Properties['Title'] contains The.White.Tiger.In.The.Yard, the the php should DIE.
I think your query needs to be (repace the single quotes around $Properties['Title'] with backtick):
$DB->query("SELECT id FROM filter WHERE `". $Properties['Title'] ."` LIKE CONCAT('%', filter, '%')");
Also, you don't need to use the concat function to prepend and append % character, you can simply use it as follows:
$DB->query("SELECT id FROM filter WHERE `". $Properties['Title'] ."` LIKE '%{$filter}%'");
could you not use
rowCount() ?
so it should look something like this:
$stmt = $DB->query("SELECT id FROM tfilter WHERE '". $Properties['Title'] ."' LIKE CONCAT('%', filter, '%')");
$numrows=$stmt->rowCount();
$error= $stmt->errorInfo();
echo $error[2];
if($numrows) {
$Err = '<b>This cant be uploaded</b>';
include(SERVER_ROOT . '/sections/upload/upload.php');
die();
Hi I am trying to get a search working for a site. It has 2 inputs for taking in info, one is a dropdown.
<div id="search">
<form action="projectsearchall.php" method="post" enctype="multipart/form-data">
<h3>Search for an Item</h3>
<p>Keywords</p><p><input name="keywords" type="text" value="keywords"></p>
<p>Select A Location</p><p>
<select name="location" id="jumpMenu">
<option>Any Location</option>
<option>Antrim</option>
<option>Armagh</option>
<option>Carlow</option>
<option>Cavan</option>
</select>
</p>
<p>
</form>
</div>
I cannot seem to figure out how to combine the 2 inputs to give a result, I can do it separately, but not working together to get a more accurate result.
php
$keywords = $_POST['keywords'];
$keylocation =$_POST['location'];
$username = $_SESSION['username'];
//MySQL Database Connect
include 'connect.php';
//make sql query
$result = mysqli_query($con,"SELECT * FROM projectitem where description like '%$keywords%' or item like '%$keywords%' or location like '%$keywords%'");
Thanks in advance!
I think you may do some preprocessing, before running your query.
First off, you need to give your select options some sort of value to check against.
I don't know your exact database structure, but assuming that you're working with the select texts, you may want to try this:
$query = "SELECT * FROM projectitem WHERE (description LIKE '%$keywords%' OR item LIKE '%$keywords%')";
This is your base query and running it right now will check against the keywords, but no location.
if($keylocation != "Any location") $query .= " AND location = '$keylocation'";
This last line will add the location as additional filter to your query. Run it, and see what it does. (I'm not sure about the string comparison there though)
Ah yes, as a final advice: Be sure to run your input through the escape function mysqli_escape_string. Otherwise you're opening yourself to SQL injections.
You're not actually using the value of $keylocation; to narrow searches down, you need an AND instead of OR:
$stmt = mysqli_prepare($con, 'SELECT * FROM projectitem
where (description LIKE ? OR item LIKE ?) AND location LIKE ?');
mysqli_stmt_bind_param($stmt, 'sss', "%$keywords%", "%$keywords%", "%$keylocation%");
mysqli_stmt_execute($stmt);
// etc.
Update
Since the drop down may have "any location" you would need to dynamically change your query:
$sql = 'SELECT * FROM projectitem WHERE 1'; // base query
$types = ''; $vars = array();
if (!empty($keywords)) {
$sql .= ' AND (description LIKE ? OR item LIKE ?)';
$types .= 'ss';
$vars[] = "%$keywords%";
$vars[] = "%$keywords%";
}
if ($keylocation != 'Any Location') {
$sql .= ' AND location LIKE ?';
$types .= 's';
$vars[] = $keylocation;
}
$stmt = mysqli_prepare($con, $sql);
if ($types) {
mysqli_stmt_bind_param($stmt, $types, $vars);
}
mysqli_stmt_execute($stmt);
first you have sql injection
use mysqli_real_escape_string
if keywords for example is null your query will be like this
$result = mysqli_query($con,"SELECT * FROM projectitem where description like '%%' or item like '%%' or location like '%$keylocation%'");
and description like '%%' return all row !
you must check data first
$query = "SELECT * FROM projectitem where 1=1 "
if($keywords)
$query .= " AND ( description like '%$keywords%' AND item like '%$keywords%' )";
if($keylocation)
$query .= " AND location like '%$keylocation%'";