Created an sql search query with having multiple fields I created using if else condition it is working fine but if 1 and 2nd field is emty and 3rd field is not then it dies not work just because of OR keyword please advise how I would be able to correct this
<form method="POST" action="search.php?action=go">
<li>
<h3>Player</h3>
<input type="text" class="form-control" placeholder="Dylan Scout" name="playername" value="<?php if(isset($_POST["playername"])) {echo $_POST["playername"];} ?>">
</li>
<li>
<h3>Age</h3>
<input type="text" class="form-control" placeholder="25" name="age" value="<?php if(isset($_POST["age"])) {echo $_POST["age"];} ?>">
</li>
<li>
<h3>Country</h3>
<input type="text" class="form-control" placeholder="Wallabies" name="country" value="<?php if(isset($_POST["country"])) {echo $_POST["country"];} ?>">
</li>
<li>
<h3>Club</h3>
<input type="text" class="form-control" placeholder="Eagle" name="club" value="<?php if(isset($_POST["club"])) {echo $_POST["club"];} ?>">
</li>
<li>
<button type="submit" name="search">Search</button>
</li>
</form>
And here is my sql php query
<?php
if(isset($_GET["action"]) == 'go') {
$stmt = "SELECT * FROM users WHERE";
if($_POST["playername"]) {
$stmt .= " OR fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$stmt .= " OR age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$stmt .= " OR country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$stmt .= " OR club LIKE '%".$_POST["club"]."%' ";
}
} else {
$stmt = "SELECT * FROM users ";
}
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>
Please let me know how would I be able to make it work properly as if i write on 3rd fields and leave other fields empty then it will become asWHERE OR which will become obviously wrong query and won't work
Thank You
The function implode will help you.
Add them into an array and connect them after.
<?php
$array = array();
if (isset($_POST["playername"]))
$array[] = "fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%";
if (isset($_POST["age"]))
...
$stmt = "SELECT * FROM users";
if (count($array) > 0)
$stmt .= " WHERE " . implode(" OR ",$array);
$sql = mysqli_query($connection, $stmt);
?>
Try this. Using implode() you can achieve this.
<?php
if(isset($_GET["action"]) == 'go') {
$where = array();
if($_POST["playername"]) {
$where[] = " OR fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$where[] = " OR age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$where[] = " OR country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$where[] = " OR club LIKE '%".$_POST["club"]."%' ";
}
if(!empty($where))
{
$stmt = "SELECT * FROM users WHERE " . implode(" AND ", $where) ." ";
}
else
{
$stmt = "SELECT * FROM users ";
}
} else {
$stmt = "SELECT * FROM users ";
}
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>
add where condition to an array, and next use implode function, for example:
<?php
if(isset($_GET["action"]) == 'go') {
$stmt = "SELECT * FROM users";
if($_POST["playername"]) {
$where[] = "fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$where[] = "age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$where[] = "country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$where[] = "club LIKE '%".$_POST["club"]."%' ";
}
if(count($where))
$stmt .= " WHERE " . implode(" OR ", $where);
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>
Related
So I have search bar that I'm hoping searches records in a mysql database and show them on a webpage. It should allow the user to choose the field they are searching under but it is is not showing the records the other end. Any ideas?
html:
<form action='recordresult.php' method='POST' name='form_filter' class="form-style-1" >
<b>Search</b><br>
<select name="selectVal">
<option value="category" >Select a category</option>
<option value="first_name">First Name</option>
<option value="surname">Surname</option>
<option value="address">Address</option>
<option value="phonenumber">Telephone</option>
</select>
<input type='text' name='search' placeholder='Enter text here...'><br>
<input type='submit' value='Send'>
</form>
PHP
<?php
include("config.php");
$link = mysqli_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysqli_error($link));
// select the database
mysqli_select_db($link, $database)
or die ("Could not select database because ".mysqli_error($link));
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM $table WHERE ";
//YOU INDICATED YOU'D NEED TO RUN THE SEARCH-QUERY IF THE SEARCH-TERM AND SEARCH-SCOPE ARE DEFINED IE: NOT NULL; HOWEVER IF THE SEARCH TERM IS NOT GIVEN, YOU SELECT EVERYTHING IN THAT TABLE... (BAD PRACTICE, THOUGH)
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}
else if($catLocation == "first_name"){
$query .= "first_name LIKE '%" . $search . "%'";
}
else if($catLocation == "surname"){
$query .= "surname LIKE '%" . $search . "%'";
}
else if($catLocation == "address"){
$query .= "address LIKE '%" . $search . "%'";
}
else if($catLocation == "phonenumber"){
$query .= "phonenumber LIKE '%" . $search . "%'";
}
}
else{
$query .= "1";
}
$sql = mysqli_query($query);
//HERE AGAIN WAS AN ERROR... YOU PASSED mysql_fetch_array A STRING $query INSTEAD OF A RESOURCE: $sql
while ($row = mysqli_fetch_array($sql)){
$firstname = $row["first_name"];
$surname = $row["surname"];
$address = $row["address"];
$phonenumber = $row['phonenumber'];
echo "First Name : $firstname<br>";
echo "Surname : $surname<br>";
echo "Address : $address<br>";
echo "Phone Number: $phonenumber<br>";
}
}
?>
The code doesn't provide any errors just a blank area where it should be. Also wondering if anyone know if it's possible to have first_name and surname as fields and search say "Emma Watson" and to be able to return results from both fields if one of the words are in there?
Thanks for all your help!
Please check below updated code
include("config.php");
$link = mysqli_connect($server, $db_user, $db_pass) or die ("Could not connect to mysql because ".mysqli_error($link));
// select the database
mysqli_select_db($link, $database)
or die ("Could not select database because ".mysqli_error($link));
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM $table WHERE ";
//**If you want to merge for first name and surname then you need to merge both query with OR condition as below**
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}
else if($catLocation == "name"){
$query .= " ( first_name LIKE '%" . $search . "%' OR surname LIKE '%" . $search . "%' ) ";
}
else if($catLocation == "address"){
$query .= "address LIKE '%" . $search . "%'";
}
else if($catLocation == "phonenumber"){
$query .= "phonenumber LIKE '%" . $search . "%'";
}
}
else{
$query .= "1";
}
$sql = mysqli_query($link, $query); // **Adding reference connection variable**
while ($row = mysqli_fetch_array($sql)){
$firstname = $row["first_name"];
$surname = $row["surname"];
$address = $row["address"];
$phonenumber = $row['phonenumber'];
echo "First Name : $firstname<br>";
echo "Surname : $surname<br>";
echo "Address : $address<br>";
echo "Phone Number: $phonenumber<br>";
}
}
Merge 2 fields (Firstname and surname) in single (name) for search in both fields
<form action='recordresult.php' method='POST' name='form_filter' class="form-style-1" >
<b>Search</b><br>
<select name="selectVal">
<option value="category" >Select a category</option>
<option value="name">name</option>
<option value="address">Address</option>
<option value="phonenumber">Telephone</option>
</select>
<input type='text' name='search' placeholder='Enter text here...'><br>
<input type='submit' value='Send'>
</form>
I have 6 input fields
<input type="text" class="form-control filter-width namef" placeholder="Product Name">
<input type="text" class="form-control filter-width brandf" placeholder="Brand Name">
<input type="text" class="form-control filter-width catf" placeholder="Category">
<input type="text" class="form-control filter-width sizef" placeholder="Size">
<input type="text" class="form-control filter-width pricef" placeholder="Price">
<input type="text" class="form-control filter-width invf" placeholder="Inventory">
each field is used to filter data. if all fields are filled then it is easy to querying data but I actually don't know using how many fields a user is going to filter. He may filter the data using only name, name and brand name, name and brand name and size, price and inventory. putting conditions using if, elseif and thinking of all possible combinations would be difficult and lengthy task.
is there any way to achieve this.
Here's my PHP:
$name = $_REQUEST['name'];
$brand = $_REQUEST['brand'];
$cat = $_REQUEST['cat'];
$size = $_REQUEST['size'];
$price = $_REQUEST['price'];
$inv = $_REQUEST['inv'];
if(!empty($name) AND !empty($brand) AND !empty($cat) AND !empty($size) AND !empty($price) AND !empty($inv) ||){
$sql = "SELECT * FROM products WHERE pname='$name' AND brand_name ='$brand' AND ptype = '$cat' AND psize= '$size' AND sprice = '$price' AND inventory='$inv'";
}
else{
}
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$pid = $row['pid'];
$pname = $row['pname'];
$pbrand = $row['brand_name'];
$pcat = $row['ptype'];
$pinv = $row['inventory'];
$pprice = $row['sprice'];
$psize = $row['psize']; ?>
<tr id="<?php echo $pid; ?>" class="prod-details"><?php echo "<td>".$pid."</td><td>".$pname."</td><td>".$pbrand."</td>"."<td>".$pcat."</td>"."<td>".$psize."</td>"."<td>".$pprice."</td>"."<td>".$pinv."</td>"; ?></tr> <?php
}
}
Now I don't know what conditions to think and write inside else body
Try following code
<?php
$sql = "SELECT * FROM products WHERE 1=1 AND ";
foreach ($_REQUEST as $key => $value) {
$columnName = '';
switch ($key) {
case 'name':
$columnName = 'pname';
break;
case 'brand':
$columnName = 'brand_name';
break;
case 'cat':
$columnName = 'ptype';
break;
case 'cat':
$columnName = 'psize';
break;
case 'size':
$columnName = 'ptype';
break;
case 'inv':
$columnName = 'inventory';
break;
}
if (!empty($columnName) && !empty($value)) {
$sql .= " $columnName='$value' AND";
}
}
$sql = rtrim($sql, 'AND');
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$pid = $row['pid'];
$pname = $row['pname'];
$pbrand = $row['brand_name'];
$pcat = $row['ptype'];
$pinv = $row['inventory'];
$pprice = $row['sprice'];
$psize = $row['psize']; ?>
<tr id="<?php echo $pid; ?>" class="prod-details"><?php echo "<td>".$pid."</td><td>".$pname."</td><td>".$pbrand."</td>"."<td>".$pcat."</td>"."<td>".$psize."</td>"."<td>".$pprice."</td>"."<td>".$pinv."</td>"; ?></tr> <?php
}
}
Also please correct me if I am wrong.
You could aggregate your query string. You may try the following-
$query = "";
if (!empty($name)) {
$query += " AND pname='$name'";
}
if (!empty($brand)) {
$query += " AND brand_name ='$brand'";
}
if (!empty($cat)) {
$query += " AND ptype = '$cat'";
}
if (!empty($size)) {
$query += " AND psize= '$size'";
}
if (!empty($price)) {
$query += " AND sprice = '$price'";
}
if (!empty($inv)) {
$query += " AND inventory='$inv'";
}
if($query != ""){
$sql = "SELECT * FROM products WHERE 1=1" . $query;
}else{
}
I'm currently working on a bit of PHP and I've 3 text inputs. The values are searched in the MySQL database and should return whatever amount of results correspond with the entered criteria.
here is the search form:
<form id='SearchPersonal' method='post' action='businessUsersSearch.php' accept-charset='UTF-8'>
<fieldset >
<legend>Search</legend>
<div class='container'>
<label for='C_Name' >Business Name: </label><br/>
<input type='text' name='C_Name' id='C_Name' maxlength="50" /><br/>
<label for='C_County' >City: </label><br/>
<input type='text' name='C_County' id='C_County' maxlength="50" /><br/>
<label for='Job_Type' >Job Type: </label><br/>
<input type='text' name='Job_Type' id='Job_Type' maxlength="50" /><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Search' />
</div>
</fieldset>
</form>
Here is the PHP script it links too in the action:
<?php
$mysqli_link = mysqli_connect("server", "database", "pass", "user");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_County', 'Job_Type');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "'$field' LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// builds the query
$query = "SELECT C_Name, C_StreetNumber, C_StreetName, C_Postcode, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Jobs.Job_Type, Jobs.Job_Price FROM Company INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysqli_query($mysqli_link, $query) or die(mysql_error());
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_assoc($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<hr><br>";
}
}
}
?>
For some reason it is returning that there is "
unexpected end of file
" however I've checked the code and all the codes is closed off correctly (from what I can see) when I add another '}' in at the end the script doesn't return anything at all. Anyone know why this would be happening?
Source:
Search MySQL Database with Multiple Fields in a Form
Because you forget to close
if(isset($_POST['submit'])) {// you not close the condition
At the end of your file
Just add } at end of your file
Fixed:
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_City', 'Job_Type', 'Review_Rate');
$conditions = array();
}
// builds the query
$query = "SELECT Company.C_Name, Company.C_StreetNumber, C_StreetName, C_Postcode, C_City, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Job_Type, Job_Price, Review_Rate, Review_Comment
FROM Company
INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID
INNER JOIN Review ON Jobs.Job_ID = Review.Job_ID";
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && !empty($_POST[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
echo "$query";
$result = mysqli_query($mysqli_link, $query);
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_array($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_City = $row['C_City'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
$Rating = $row['Review_Rate'];
$Comment = $row['Review_Comment'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>City: $C_City<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<br>Rating: $Rating<br>Comment: $Comment<hr><br>";
}
}
?>
this code gives no result even if the word exists in database
<?php
$query = $_GET['query'];
$min_length = 3;
if (strlen($query) >= $min_length) {
$query = htmlspecialchars($query);
$query = $DB_con->quote($query);
$raw_results = $DB_con->prepare("SELECT * FROM e3lanat
WHERE (`e_title` LIKE '%" . $query . "%') OR (`e_content` LIKE '%" . $query . "%')");
if ($raw_results->rowCount() > 0) {
while ($results = $raw_results->fetch(PDO::FETCH_OBJ)) {
echo "<p><h3>" . $results->e_title . "</h3>" . $results->e_content . "</p>";
}
} else {
echo "No results";
}
} else {
echo "No results 2";
}
?>
<form action="search.php" method="GET">
<input type="text" name="query" class="form-control" placeholder="بحث عن إعلانات " style='width:300px;'>
<button type="submit" value="Search"></button>
</form>
$raw_results = $DB_con->prepare("SELECT * FROM e3lanat
WHERE (`e_title` LIKE '%".$query."%') OR (`e_content` LIKE '%".$query."%')");
if($raw_results->rowCount() > 0){
You only prepare() the query, but not execute()-ing it.
In form user need to check options who will receive newsletter, for example:
<input type="checkbox" name="male" value="1" />
<input type="checkbox" name="female" value="1" />
<input type="checkbox" name="person" value="1" />
<input type="checkbox" name="company" value="1" />
But I have problem how to create query for db with checked options
I have this code so far, but it is not good, because newsletter need to be 1 all the time and after that I have OR, because when I put AND I don't get the results that I need:
if($options['male']) {
$sqlAddMale = " OR gender = 2 ";
}
if($options['female']) {
$sqlAddFemale = " OR gender = 1 ";
}
if($options['person']) {
$sqlAddPerson = " OR VAT = '' ";
}
if($options['company']) {
$sqlAddCompany = " OR VAT <> '' ";
}
$query = "
SELECT email FROM users WHERE newsletter=1
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";
I think You need something like this:
$placeOr = false;
if($options['male']) {
$placeOr = true;
$sqlAddMale = " (newsletter=1 AND gender = 2) ";
}
if($options['female']) {
$sqlAddFemale = (($placeOr)?" Or ":"");
$sqlAddFemale .= " (newsletter=1 AND gender = 1) ";
$placeOr = true;
}
if($options['person']) {
$sqlAddPerson = (($placeOr)?" Or ":"");
$sqlAddPerson .= " (newsletter=1 AND VAT = '') ";
$placeOr = true;
}
if($options['company']) {
$sqlAddCompany = (($placeOr)?" Or ":"");
$sqlAddCompany .= " (newsletter=1 AND VAT <> '') ";
$placeOr = true;
}
$query = "
SELECT email FROM users WHERE
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";
Here is how you can solve your issue, use one variable to build up your where clause, use AND operater when you are adding the first condition, else use OR
$sqlString = '';
if($options['male']) {
$sqlString = " AND gender = 2 ";
}
if($options['female']) {
if(!$sqlString) $sqlString = " AND gender = 1 ";
else
$sqlString .= " OR gender = 1 ";
}
if($options['person']) {
if(!$sqlString) $sqlString = " AND VAT = '' ";
else
$sqlString .= " OR VAT = '' ";
}
if($options['company']) {
if(!$sqlString) $sqlString = " AND VAT <> '' ";
else
$sqlString .= " OR VAT <> '' ";
}
$query = "SELECT email FROM users WHERE newsletter=1'".$sqlString."'";