multiple field search form displaying entire database [duplicate] - php

This question already has answers here:
Search Form with One or More (Multiple) Parameters
(2 answers)
Closed 7 years ago.
I am trying to create a database with multiple fields for searching but it is displaying the entire database if there is an empty field. i suspect it is because of the OR's in the query and i am not sure how to fix it.
<?php
if (isset($_POST['Submit']))
{
$con = mysqli_connect();
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$surname = $_POST['surname'];
$firstname = $_POST['firstname'];
$maiden = $_POST['maiden'];
$birth = $_POST['birth'];
$death = $_POST['death'];
$keyword = $_POST['keyword'];
$sql = "SELECT * FROM obits WHERE surname LIKE '%" . $surname . "%' OR firstname LIKE '%" . $firstname . "%' OR maiden LIKE '%" . $maiden . "%' OR birth LIKE '%" . $birth . "%' OR death LIKE '%" . $death . "%' OR obittext LIKE '%" . $keyword . "%'";
$result = mysqli_query($con, $sql);
further down i have this:
if (isset($result) && $result->num_rows > 0);
then follows the table etc. i think i have all the pertinent info here. any suggestions? please use english rather than programmer, i am quite new at this. thanks in advance!

Let's look at one of the conditions:
surname LIKE '%" . $surname . "%'
Assuming, $surname is Miller here, you select all rows that have a surname like %Miller%. The % signs are wildcards, which can basically stand for anything. This means you are selecting all rows where the surname contains Miller with any string before or after it, including empty ones.
Now, if Miller would be empty in this case, you are looking for %%, so an empty string with anything before or after it -- so really any possible string. As a result, every row will be selected.
Since this is true not only for the surname, but for any of the columns, leaving any of the criteria blank will result in all rows being selected.
Find more info on SQL Wildcards.
To skip empty values in your where clause, you can build it dynamically:
$condition = "WHERE";
if(!empty($surname)){
$condition .= "surname LIKE '$surname' OR";
}
if(!empty($firstname)){
$condition .= "firstname LIKE '$firstname' OR";
}
// ...
$sql = "SELECT * FROM obits " . $condition;
Note:
There will be a trailing OR in the condition that you will have to remove.
If all conditions are blank, this will also lead to an error.
But it should give you an inpiration! :-)
Side Note:
You should look into prepared statements. Passing POST variables directly into an SQL statement is highly dangerous.

Related

Search result page leading to a specific page [up]

I am creating a database website wherein there is a search bar then it will lead to a search results page (in table form). The user will then select a specific result that would lead to a custom webpage for that result. Is there a way to do that in PHP/MYSQL?
Here is my PHP code:
<?php
include "databaseconnect.php";
$keywordfromform = $_GET["Search"];
$sql = ("SELECT titleID, authorsID, yearID, subjectID
FROM researchpapertable
WHERE titleID LIKE '%" . $keywordfromform . "%'
OR authorsID LIKE '%" . $keywordfromform . "%'
OR yearID LIKE '%" . $keywordfromform . "%'
OR subjectID LIKE '%" . $keywordfromform . "%'
");
$result = $mysqli->query($sql);
if ($result-> num_rows>0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<tr><td>'. $row["titleID"]."</td><td>". $row["authorsID"]."</td><td>". $row["yearID"]."</td><td>". $row["subjectID"]."</td></tr>";
}
} else {
echo "<tr><td> 0 results </td><td> 0 results </td><td> 0 results </td><td> 0 results </td><tr>";
}
$mysqli->close();
?>
I placed a <a href="indivpage.php"> in the column where they will select the title of their choice. What should I place there for it to lead to its specific page? I am not sure what I should search for in order to search for similar tutorials/code. If there are similar questions/code to this, it would help a lot. Thank you in advance!
You would send a unique identifier as a parameter to your page. Like this:
echo '<tr><td>' . $row["titleID"] . '...etc...</td></tr>';
Then in your indivpage.php you would use $_GET['title_id'] to fetch all the details from the database.
Let me add to this that there is very much wrong with the code you wrote. To begin with I would suggest to read about SQL injection

mysql like query, how can you sort targeting two columns in a table but sorting by the results matched by one column

Using the code below, i am able to return all products that match the search word. However they order in a way that a product with a name different from the search phrase appears first and one with a matching name later because the description had a match.
How can i sort and return the products whose name matches the search phrase first?
$sqli = "
SELECT *
FROM product
WHERE";
Foreach($strarray as $key=>$value){
If($key > 0){
$sqli = $sqli . "OR";
}
$sqli = $sqli . " (Name LIKE '%" . $value . "%' or Description LIKE '%" . $value . "%')";
}
Add an ORDER BY clause:
$ssql .= " ORDER BY Name LIKE '%" . $value . "%' DESC"
A boolean expression is 1 for TRUE and 0 for FALSE, so sorting by a condition orders by whether the row matches the condition.
BTW, you should learn to use prepared statements to prevent SQL injection. See How can I prevent SQL injection in PHP?

mysqli_query don't work in PHP

Im trying to make an easy Select from the db and save the results in an array.
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '%; " . $autor2 . "%';";
echo($query);
// get IDs
$res = mysqli_query($link,$query );
$i = 0;
while ($row = mysqli_fetch_assoc($res)){
echo($row['ID']);
$IDarray[$i]= $row['ID'];
$i++;
}
The $autor2 variable is an Name like: "Doe, John".
The code seems to not go in the loop, and mysqli_error after the loop is null so it seems im not getting results from the db.
When im copying the echo from $query in phpMyAdmin it works fine. Also when im using a Name instead $autor2 it also works fine and im getting my whole Array.
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '%" . $autor2 . "%'";
write this code.
As far as I can see in the SQL query, there's a syntax error.
You wrote :
SELECT ID FROM Publikationen WHERE Personen LIKE '%; " . $autor2 . "%';
but it should have been :
SELECT ID FROM Publikationen WHERE Personen LIKE '%" . $autor2 . "%';
Hope it helps!
Remove the semicolon from the query.
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '% " . $autor2 . "%'";
Simply use this -
$query = "SELECT ID FROM Publikationen WHERE Personen LIKE '%$autor2%'";
If the semicolon is important then use it but use the $author2 variable just inside single quote (' ').

MySQL - Searching & Conaining word / PHP

I'm trying to search an element into two different column of a MySQL database. The first may match the searchedObject the second may contain it (the column contain text). I'm using PHP
The page return me an error :
Parse error: syntax error, unexpected ')' in C:\wamp\www\v2\header.php on line 9
Here is my request
"SELECT * FROM corporate WHERE (columnA = " . $_GET["searchedObject"]) . " OR (columnTextedB LIKE '%" . $_GET["searchedObject"] . "%' )";
Any idea to save my night :o ?
The error is pretty clear on what you have done wrong...
$_GET["searchedObject"])
Move that )... into
") OR (columnTextedBLIKE '%"
PS. this code is very vulnerable to sql injection attacks
The syntax error is a problem in your PHP:
"SELECT * FROM cim_corporate WHERE (columnA = " . $_GET["searchedObject"]) . " OR (columnTextedBLIKE '%" . $_GET["searchedObject"] . "%' )";
Note that you close a bracket that is never opened in PHP. Try:
"SELECT * FROM cim_corporate WHERE (columnA = " . $_GET["searchedObject"] . ") OR (columnTextedBLIKE '%" . $_GET["searchedObject"] . "%' )";
However please do not use $_GET variables directly in queries. A malicious user can then add all sorts of nasty stuff to your query.

Escaping % symbol in MySQL with PHP

i have a simple search box but I am trying to avoid the result page returning all results in table when the query is %. how can that be done?
I think you want to use \%...
In your PHP,
$query = str_replace ( '%' , '\%' , $query )
$sql = "SELECT * FROM table WHERE column LIKE '%" . mysqli_real_escape_string($query) . "%'"
Are you sanitizing your inputs?
You can start with mysqli_real_escape_string()
$query = "SELECT * FROM table WHERE column LIKE '" . mysqli_real_escape_string($input) . "'";

Categories