I have a PHP program that allows users to search through an SQL table depending on the input or combination of inputs. I can do single search combination, but can't figure out a way to search by any criteria. What I got so far is terrible because I'm trying to search by every input possibility (and it's not working). This is what I got so far.
<?php
include_once("config.php");
if(isset($_POST['submit'])){
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$day = mysqli_real_escape_string($mysqli, $_POST['day']);
$month = mysqli_real_escape_string($mysqli, $_POST['month']);
$year = mysqli_real_escape_string($mysqli, $_POST['year']);
// 1 2 3 4
if( !empty($name) && !empty($day) && !empty($month) && !empty($year) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE name like '%$name%'
and day LIKE '%$day%'
AND month LIKE '%$month%'
AND year LIKE '%$year%'");
} else if (!empty($name) && !empty($day) && !empty($month) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE name like '%$name%'
and day LIKE '%$day%'
AND month LIKE '%$month%'");
} else if (!empty($day) && !empty($month) && !empty($year) ) {
$sql = mysqli_query($mysqli, "SELECT *
FROM transfer
WHERE day LIKE '%$day%'
AND month LIKE '%$month%'
AND year LIKE '%$year%'");
} else if (!empty($name && !empty($day) ) {
$sql = mysqli_query($mysqli, "SELECT * FROM transfer
WHERE name like '%$name%' and
day LIKE '%$day%'");
}
//1 3
else if (!empty($name) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%' and month LIKE '%$month%'");
}
//1 4
else if (!empty($name) && !empty($year) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%' and year LIKE '%$year%'");
}
//2 3
else if (!empty($day) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and month LIKE '%$month%'");
}
//2 3
else if (!empty($day) && !empty($month) )
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and month LIKE '%$month%'");
}
//2 4
else if (!empty($day) && !empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%' and year LIKE '%$year%'");
}
//3 4
else if (!empty($month) && !empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE month like '%$month%' and year LIKE '%$year%'");
}
//1
else if (!empty($name))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE name like '%$name%'");
}
//2
else if (!empty($day))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE day like '%$day%'");
}
//3
else if (!empty($month))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE month like '%$month%'");
}
//4
else if(!empty($year))
{
$sql = mysqli_query($mysqli, "SELECT * FROM transfer WHERE year like '%$year%'");
}
else
{
echo "<p>you must insert an input</p>";
}
//while loop used to retrieve data from the SQL database
while ($res = mysqli_fetch_array($sql))
{
echo "<tr>";
echo "<td>".$res['name']."</td>";
echo "<td>".$res['confirmation']."</td>";
echo "<td>".$res['code']."</td>";
echo "<td>".$res['hora']." ".$res['horario']."</td>";
echo "<td>".$res['day']."/".$res['month']."/".$res['year']."</td>";
echo "<td>".$res['extra']."</td>";
echo "</tr>";
}
}
?>
</table>
(Note: It has been said to use prepared statements, which is right - but I don't want to give a copy & paste answer anyway, so here is just an example on how you can achieve your result - use prepared statements anyway. It works the same, except you are creating your query with placeholders and provide the variables that are not empty)
You can create your query in a more "dynamic" way. This is a little tricky, and becomes very "challenging" if joins are required - but what you actually want is to end up with a single query, containing all your constraints.
The first thing, you should define: Are your Searchfields "and" or "or" fields?
if it's "and" it is quite simple to achieve - something like this:
$query = "SELECT * FROM transfer";
$andParts = array();
if(!empty($name))
$andParts[] = "name = '$name'";
if(!empty($day))
$andParts[] = "day = $day";
if (!empty($month))
$andParts[] = "month = $month";
if (!empty($year))
$andParts[] = "year = $year";
if (!empty($andParts))
$query .= " WHERE ".implode(" AND " , $andParts);
$sql->Query($query);
if theres also "or" involved, you'll need another array $orParts, where you first join all the "ors", and finally glue that array together to the final "ands".
If conditions could match columns from "joined" tables, you need to keep track of that, so that you know, from with tables you need to "select".
If you have very complex query for each "searchfield" (i.e. every searchfields result is a result of multiple joins etc...) you can query just the id's for each searchfield, then intersect the results and retrieve the ids matching all criterias:
$result1 = $sql->Query("SELECT id FROM transfer left join .... ");
// array(1,2,3,5,7,10,15,19,27)
$result2 = $sql->Query("SELECT id FROM transfer right join .... ");
// array(2,3,10,15,19,27,43,123)
$result3 = $sql->Query("SELECT id FROM transfer inner join .... ");
// array(2,10,15,27,43,711)
$ids = array_intersect($result1, $result2, $result3);
// array(2,10,15,27)
$finalResult = $sql->Query("SELECT * FROM transfer WHERE id in (".implode(",", $ids).");");
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;
}
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";
}
I'm creating a search toolbar on my web page to allow the user to identify what column to search, and what operator to use to search that column. To avoid having a lot of if statements, I want to write the SQL like this:
if ($operator == "LIKE") {
sql = "SELECT * FROM `mytable` WHERE `$column` '$operator' '%$search%'";
} else {
sql = "SELECT * FROM `mytable` WHERE `$column` '$operator' '$search'";
}
This works fine if the operator is LIKE, but when it is =, it doesn't work. I've checked the array that is posted to the page, and have confirmed that the array is posting correctly. How do I make this work when the operator is "=" ? Here is the array:
Array
(
[column] => first_name
[operator] => =
[search] => paul
[page_rows] => 10
)
It would run removing ' around operators:
if ($operator == "LIKE") {
sql = "SELECT * FROM `mytable` WHERE `$column` $operator '%$search%'";
} else {
sql = "SELECT * FROM `mytable` WHERE `$column` $operator '$search'";
}
but maybe it's better to just use:
if ($operator == "LIKE") {
sql = "SELECT * FROM `mytable` WHERE `$column` LIKE '%$search%'";
} else {
sql = "SELECT * FROM `mytable` WHERE `$column` = '$search'";
}
do not use single quotes ' on $operater. it will be better to use LIKE or = directly.
I am trying to make my coding more efficient and I am stuck at how to tell the query to display all the categories if nothing is selected.
I have 15 categories that the user can chose from, if none is selected, display all items. Rather than doing AND .. AND .. AND 15 times if nothing is selected, is there a smarter way for this?
This will work for one category selection:
$cate = mysql_query("SELECT * FROM `posts` ORDER BY `id` ASC");
while($row = mysql_fetch_assoc($cate)){
if($user_data['category'] === $row['id']) {
echo '<li>'.$row['name'].'</li>';
}
}
$category_list = "AND `category_id` = '".$user_data['category']."'";
You should generate your query dynamically
// General query
$query = "SELECT * FROM `posts`";
// If category selected
if ($user_data['category'] != 0) {
$query .= " WHERE `category_id` = '".$user_data['category']."'";
}
// Order
$query .= " ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);
Or it can be simplified using Ternary Operator:
// Generate query
$query = "SELECT * FROM `posts` ".($user_data['category'] != 0 ? "WHERE `category_id` = '".$user_data['category']."'" : "" )." ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);