PHP mysql query 2 OR and 1 AND - php

$query = "SELECT * FROM tbl_country WHERE language='$lang' AND country_name LIKE '%".$_POST["query"]."%' OR country_second LIKE '%".$_POST["query"]."%'";
The above will not work. I want it to search in 2 fields (works) but based of the language I've set. But it simply skips the lang part

Try this
$search = $_POST["query"];
if(empty($search))
{
echo "Search filed is empty";
}
elseif (empty($lang)) {
echo "Lang filed is empty";
}
else
{
$query = "SELECT * FROM tbl_country WHERE language='$lang' AND
(country_name LIKE '%$search%' OR country_second LIKE '%$search%') ";
}
Wrap with ()

Related

mysql multiple word search

i have a mysql table and a search form
i am filtering the table acc to the given conditions
but my problem is i want to search multiple words from string field
could you please help me how to do this :
i mean i want to allow it to be written multiple words in the string and want them to be searched by "AND"
if ($_REQUEST["string"]<>'') {
$search_string = " AND (customername LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR definition LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}
if ($_REQUEST["customername"]<>'') {
$search_customername = " AND customername='".mysql_real_escape_string($_REQUEST["customername"])."'";
}
if ($_REQUEST["date"]<>'' and ($_REQUEST["string"]<>'' or $_REQUEST["customername"]<>'') ) {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ".$search_string.$search_customername;
} else
if ($_REQUEST["date"]<>'' and ($_REQUEST["string"]<>'' or $_REQUEST["customername"]<>'' ) ) {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ".$search_string.$search_customername;
} else
if ($_REQUEST["date"]<>'' and $_REQUEST["string"]=='' and $_REQUEST["customername"]=='') {
$sql = "SELECT * from ".$SETTINGS["data_table"]." WHERE date = '".mysql_real_escape_string($_REQUEST["date"])."' ";
} else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE id>0".$search_string.$search_customername;
}

Search multiple values if present

sorry my English is weak ....
how can i search multi values from db SQL So that there was any.
i can search name && family together but
I want when the user searched name And family leave empty Return result correctly
how can i write this
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE name='{$_POST['searchname']}' && family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Your 3 main issues here..
the first being WHERE name= now.. name is already used by mysql therefore you shouldn't use it however.. If you do use it run it like this:
WHERE `name`=
You should always backtick database tables and columns to make life easier in the long haul.
The second issue being you used && where it should be AND
the third is you shouldn't be placing your variables straight into your query as you're left open for SQL Injection.
Now I'm running on the assumption you're using $mysqli as your variable however, this may need adjusting to suit the correct variable you are using:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$searchName = $_POST['searchname'];
$family = $_POST['searchfamily'];
$sql = $mysqli->prepare("select * from `myinfo` WHERE `name` = ? OR `family`= ? ORDER BY `id` DESC");
$sql->execute([$searchName, $family]);
} else {
$sql = $mysqli->prepare("select * from `myinfo` ORDER BY `id` DESC");
$sql->execute();
}
If you want to search with both then you need to change your if also. And change && to and in your query
if (isset($_POST['searchname']) && isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE `name`='{$_POST['searchname']}' AND family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Edit
As per your comment try this:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$where="";
if(isset($_POST['searchname']))
$where=" WHERE `name`='{$_POST['searchname']}'";
if(isset($_POST['searchfamily']))
{
if($where=="")
$where=" WHERE family='{$_POST['searchfamily']}'";
else
$where=" AND family='{$_POST['searchfamily']}'";
}
$sql = "select * from myinfo $where ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}

php MySQL select priority

$query = "SELECT * FROM posts WHERE language='$lang' AND (title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')";
This does exactly what it should do. But what I'd like to do is having "title" as a priority. But as it looks now (every search is in a dropdown of html) it simple show's it without an priority. So the title can be at the very bottom, and the author at the top. Wrong order. I'd like to somehow always have the title at top.
How?
$output = '';
$lang = $_SESSION["lang"];
$search = $_POST["query"];
$query = "SELECT * FROM posts WHERE language='$lang' AND (title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')";
$result = mysqli_query($connect, $query);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$output .= '</ul>';
echo $output;
You can split up the query.
$output = '';
$lang = $_SESSION["lang"];
$search = $_POST["query"];
$query2 = "SELECT * FROM posts WHERE language='$lang' AND title LIKE '%$search%'";
$result2 = mysqli_query($connect, $query2);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$query = "SELECT * FROM posts WHERE language='$lang' AND (author LIKE '%$search%' OR year LIKE '%$search%')";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$output .= '</ul>';
echo $output;
ORDER BY should do the trick for you here:
http://www.w3schools.com/sql/sql_orderby.asp
$query = "
SELECT book
, title
, url
FROM posts
WHERE language='$lang'
AND (
title LIKE '%$search%'
OR
author LIKE '%$search%'
OR
year LIKE '%$search%'
)
ORDER BY title ASC
, author ASC
, book ASC
";
I've added an optional order by 'author' and 'book' too (the priority of ordering starts with 'title', then 'author' and finally 'book') - you can change this to whatever you need though in ASC (ascending) or DESC (descending) order.
I'd also recommend you consider using bind params rather than passing in variables directly into your SQL to prevent SQL Injection.
Mysqli Bind Param Documentation
http://php.net/manual/en/mysqli-stmt.bind-param.php
Really good SO post here with help and more info about SQL Injection
How can I prevent SQL injection in PHP?
Also - try to avoid using SELECT * FROM... where possible, and only SELECT out the information you need. You'll be able to INDEX it better this way too (meaning quicker retrieval of data from the database).
You could use a scoring system to give each match a score and then sort by the match score. So a match for title gets a higher score and a match for author gets the next highest and so on. I'll rewrite just the query here:
SELECT *,
(
CASE
WHEN title LIKE '%$search%' THEN 100
WHEN author LIKE '%$search%' THEN 10
WHEN year LIKE '%$search%' THEN 1
END
) AS matchScore
FROM posts
WHERE
language='$lang' AND
(title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')
ORDER BY matchScore DESC

mysql full text search not working

i am trying to work with MySQL full text search in table
query:
$text="MySQL HTML";
$sql="SELECT * FROM search
WHERE MATCH (title,title_info) AGAINST ('$text' IN BOOLEAN MODE)";
it is supposed to return all rows having both MySQL HTML or MySQL or HTML,
but its not resulting any thing why?
You must add + sign as prefix to each search term:
$text="MySQL HTML";
$text_array = split(' ',$text);
$search_terms = '+'.join($text_array,' +'); // +MySQL +HTML
$sql="SELECT * FROM search
WHERE MATCH (title,title_info) AGAINST ('$search_terms' IN BOOLEAN MODE)";
Read more about fulltext search:
http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html
Try this one
$text="MySQL HTML";
$sql=" SELECT * FROM search
WHERE title LIKE '%$text%' OR
title_info LIKE '%$text%'";
Try to implement this function will search full text
$text = "Test String For You";
$bquery .= getwQuery($text,'title,title_info');
$sql="SELECT * FROM search WHERE ".$bquery;
echo $sql;
function getwQuery($data, $field_name)
{
$names_exploded = explode(" ", $data);
$fname = explode(",", $field_name);
foreach($names_exploded as $each_name)
{
if($each_name != ""):
$bquery .= " AND (";
foreach($fname as $fn)
{
$bquery .= $fn." LIKE '%".$each_name."%' OR ";
}
$bquery = rtrim($bquery,' OR ');
$bquery .= ')';
endif;
}
$bquery = ltrim($bquery,' AND ');
return $bquery;
}
Output:
SELECT * FROM search WHERE (title LIKE '%Test%' OR title_info LIKE '%Test%') AND (title LIKE '%String%' OR title_info LIKE '%String%') AND (title LIKE '%For%' OR title_info LIKE '%For%') AND (title LIKE '%You%' OR title_info LIKE '%You%')

How to create <form> for search with assoc array

Hello can u help me with a script that i have trouble with ;\ i want to create a search script from different columns and price range: so the search.php is that:
<?php
/* connect to the database*/
$db = new mysqli("localhost", "root", "", "movie");
/* check connection */
if ($db->connect_errno) {
echo "Connection failed: " . $db->connect_error;
exit();
}
$query="SELECT * FROM `filmi`
WHERE (`nomer` rlike '%$search%' OR
`rezume` rlike '%$search%' OR
`kategoriq` rlike '%$search%') AND
`seriq` BETWEEN '%$pricemin%' AND '$pricemax'
ORDER BY seriq ASC";
/* create a prepared statement */
if ($stmt = $db->prepare($query)) {
/* bind parameters for markers */
$stmt->bind_param("sssdd", $search, $search, $search, $pricemin, $pricemax);
/* execute query */
$stmt->execute();
/* get result */
$result = $stmt->get_result();
if ($result) {
/* now you can fetch the results into an assoc array */
while ($row = $result->fetch_assoc()) {
echo $row['nomer']. ", " .$row['rezume']. ", " .$row['kategoriq']. ", " .$row['seriq']. "<br>";
}
}
/* close statement */
$stmt->close();
}
/* close db connection */
$db->close();
?>
What shoud be the "<form method=?>" form fill the $search and $pricemin / $pricemax fields ?
Check whether $search exists or not. Means, does there is some value in $search or not.
if(isset($search) && $search!=''){
case 1
}
else{
case 2
}
Case 1:
If there is value in $search then include it in where clause.
below query is an example to explain my idea.
$query="SELECT * FROM `filmi`
WHERE (`nomer` rlike '%$search%' OR
`rezume` rlike '%$search%' OR
`kategoriq` rlike '%$search%') AND
`seriq` BETWEEN '%$pricemin%' AND '$pricemax'
ORDER BY seriq ASC";
Case 2:
If there is no value in $search then does not include it in where clause.
check below query
$query="SELECT * FROM `filmi`
WHERE `seriq` BETWEEN '%$pricemin%' AND '$pricemax'
ORDER BY seriq ASC";
You can use either GET or POST method in your <form> tagg
and
in your PHP script you can use $form_var_name = $_REQUEST['form_var_name'] to access the data dispatched by form. To be more specific as follows
$search = $_REQUEST['search'];
$pricemin = $_REQUEST['pricemin'];
$pricemax = $_REQUEST['pricemax'];

Categories