I would like to create a search system that is able to filter general search results in more narrow way according to users specification.
For example, a user first performs general search of places and then the search system lists all users from that place and in the next step user wants to filter this user list according to the age.
The code below does general search for users from the specific place, and it also filters search results according to the age only if the keyword is specified in the search box and age group is selected before submitting.
What I want to achieve is that, users are able to filter results instantly after the general search is submitted. For example the general search results are John, Mary, Robert, and in the next step user selects age group 18-25 and the system instantly filters name John.
Any idea how to do this is very welcome!
This is php code:
<?php
include_once("php_includes/db_travel_vowel.php");
$search_output = "";
$search_output1 ="";
$username ="";
$age_form ="";
if(isset($_POST['searchquery']) && $_POST['searchquery'] != ""){
$searchquery = preg_replace('#[^0-9a-z]#i', '', $_POST['searchquery']);
$sqlCommand = "(SELECT * FROM users WHERE country LIKE '%$searchquery%' OR town LIKE '%$searchquery%' OR city LIKE '%$searchquery%')";
$query = mysqli_query($cn, $sqlCommand) or die(mysqli_error($cn));
$count = mysqli_num_rows($query);
if($count >= 1){
$search_output .= "<hr />$count results for <strong>$searchquery</strong><hr />";
while($row = mysqli_fetch_array($query)){
$url = $row["url"];
$f_name = $row["f_name"];
$l_name = $row["l_name"];
$user = $f_name;
$user.= " ";
$user.= $l_name;
$username = $row["username"];
if($_POST['age'] == "1" || $_POST['age'] == "2" || $_POST['age'] == "3" || $_POST['age'] == "4" || $_POST['age'] == "5" ){
$age=$_POST['age'];
$sqlC = "(SELECT f_name, l_name, url FROM users WHERE username='$username' AND age_group='$age')";
$query1 = mysqli_query($cn, $sqlC) or die(mysqli_error($cn));
while($row1 = mysqli_fetch_array($query1)){
$url1 = $row["url"];
$f_name1 = $row["f_name"];
$l_name1 = $row["l_name"];
$user1 = $f_name;
$user1.= " ";
$user1.= $l_name;
$username1 = $row["username"];
$search_output .= ''. $user1 .'<br>';
}
} else {
$search_output .= ''. $user .'<br>';
}
} // close while
} else {
$search_output = "<hr />0 results for <strong>$searchquery</strong><hr />$sqlCommand";
}
}
?>
HTML code:
<form id="search_new" action="index_search1.php" method="post">
<input name="searchquery" type="text" size="70" maxlength="88" placeholder="Search for places and members..." />
<input type="submit" />
<div id="options">
<select name="age">
<option selected>Age group<option>
<option value="1">18-28<option>
<option value="2">29-39<option>
<option value="3">40-50<option>
<option value="4">51-61<option>
<option value="5">62-more<option>
</select>
</div>
</form>
<?php echo $search_output; ?>
Thank you very much!
Related
To clarify title, here's my code. It's not working--I'm sure it's wrong. But I don't know if I'm close or far away from the answer. I have an "Any" option that I want to reveal everything in my database as opposed to the selected option which would only reveal specific rows. I'm not sure how to display the former. Thanks!
$Interest = $_GET['interestId'];
$sql = "SELECT * from User WHERE (Interest1 = '$Interest' OR Interest2 = '$Interest' OR Interest3 = '$Interest' OR $Interest = 'Any Interest');";
$result = mysqli_query($link, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<p>";
echo Name . ": ";
echo $row['Fname'] . " ";
echo $row['Lname'] . "<br><br>";
echo Interests . ": ";
echo $row['Interest1'] . ", ";
echo $row['Interest2'] . ", ";
echo $row['Interest3'] . "<br><br>";
echo Website . ": ";
echo $row['Website'] . "<br><br>";
echo Personal_Statement . ": <br><br>";
echo $row['PersonalStatement'] . "<br><br>";
echo Contact . ": ";
echo $row['Phone'] . "<br>";
echo $row['Email'];
echo "</p>";
}
} else {
echo "<h2>Drat!</h2> There's currently no one with the interest of $Interest!";
}
Now it doesn't return anything for any selection.
So if $Interest is "Any" then there should be no filter at all? You can put that logic in the query. For example, consider something like this:
SELECT *
FROM User
WHERE
(Interest1 = '$Interest' OR Interest2 = '$Interest' OR Interest3 = '$Interest')
OR '$Interest' = 'Any'
Under this logic that last OR will match every record if the variable has the string "Any". So you're basically saying "if the record matches the input, OR if the input is Any".
Also, and this is important, your code is wide open to SQL injection. What that means is that you blindly execute any code your users send you. This answer demonstrates the logic of a solution, but there is more you need to do. Start by learning what SQL injection is here, and some quick information about how to meaningfully prevent it here.
the question that you have written is not clarifying us but the went i through you code and perceived u want to fetch the data from database in four situation
1. for any interest
2. interest1
3. interest2
4. interest3
to achieve desired result u would have to make some change to you submission form as well as in php code. here in am going to write both the code for html as well as php hope it would be helpful to you
<form action="action.php" method="GET">
<select type="text" name="interestID"> --select interest type--
<option value="AnyInterest">Any Interest</option>
<option value="interest1">interest1</option>
<option value="interest2">interest2</option>
<option value="interest3">interest3</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
// php code
<?php
if(isset($_GET['submit'])){
$interestId = $_GET['interestID'];
// connect with database query
switch($interestId){
case "AnyInterest":
$data = mysql_query("SELECT * FROM user") or mysql_error();
break;
case "interest1":
case "interest2":
case "interest3":
$data = mysql_query("SELECT * FROM user WHERE interestId = '$interestId '") or mysql_error();
break;
}
$count = mysql_num_rows($data);
if($count > 0){
while ($rows = mysql_fetch_assoc($data)){
// write code here to display the content on webpage
}
}else{
header(Location: action.php);
}
?>
I suppose your form/ajax is this:
<input id="anyInterest" name="nome" type="text" />
In php you can do:
$any = $_GET['anyInterest'];
$sql = "SELECT * FROM user WHERE Interest = " +$any "OR Interest = 'Any Interest'";
$result = mysqli_query($link, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
//do something
}
else {
echo "<h2>Drat!</h2> There's currently no one with the interest of $Interest!";
}
Best choice for security:
$any = $this->input->get('anyInterest');
$sql = "SELECT * FROM user WHERE Interest = " +$any "OR Interest = 'Any Interest'";
$result = mysqli_query($link, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
//do something
}
else {
echo "<h2>Drat!</h2> There's currently no one with the interest of $Interest!";
}
If this is not the right answer, could you explain the process better, your idea?
I'm trying to get certain data which meets the criteria from the database using AND condition with user searchable HTML form which sends the data to the search.
Code:
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
if (isset($_POST['Kohderyhmä']) &&
isset($_POST['Näytön aste']) &&
isset($_POST['Vaikutusten vahvuus']) &&
isset($_POST['Käyttökelpoisuus']) &&
isset($_POST['text']))
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
$Näytön_aste = get_post($conn, 'Näytön aste');
$Vaikutusten_vahvuus = get_post($conn, 'Vaikutusten vahvuus');
$Käyttökelpoisuus = get_post($conn, 'Käyttökelpoisuus');
$text = get_post($conn, 'text');
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='$Kohderyhmä' AND `Näytön aste`='$Näytön_aste' AND `Vaikutusten vahvuus`='$Vaikutusten_vahvuus' AND `Käyttökelpoisuus: luokka`='$Käyttökelpoisuus'";
}
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
echo '<h3>' . $row['Nimi'] . '</h3><br />';
echo '' . $row['Kokonaisarvio'] . '<br />';
echo '' . $row['Kuvaus'] . '<br /><br />';
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<b>Kohderyhmä</b><br />
<select name="Kohderyhmä" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Pikkulapset">Pikkulapset</option>
<option value="Alle kouluikäiset">Alle kouluikäiset</option>
<option value="Alakouluikäiset">Alakouluikäiset</option>
<option value="Nuoret">Nuoret</option>
<option value="Perheet">Perheet</option>
<option value="Vanhemmat">Vanhemmat</option>
<option value="Työntekijät">Työntekijät</option>
</select>
<br />
<b>Näytön aste</b>
<select name="Näytön aste" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei riittävää näyttöä">Ei riittävää näyttöä</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Vaikutusten vahvuus</b>
<select name="Vaikutusten vahvuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei vaikutusta">Ei vaikutusta</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Käyttökelpoisuus</b>
<select name="Käyttökelpoisuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei käyttökelpoinen">Ei käyttökelpoinen</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<br />
Haku: <input type="text" name="text" />
<input type="submit" value="Hae" />
</form>
I haven't used PHP to contact database before so the PHP code is very messy.
I don't understand any more than the very basics from PHP, I haven't used variables or objects or anything complex before.
HTML form:
variable1
variable2
variable3
variable4
variable5
--->
PHP script:
select * from db
where variable1 and variable2 and variable3 and variable4
--->
display results matching the criteria
Current code causes this error message in error_log:
PHP Warning: mysqli::query(): Empty query in /home/user/public_html/folder/script.php on line 23
I have already tried over 15 different variations of variables and sql query in total and nothing has worked..
If we shorten your if (isset($_POST ... something you can clearly see. This instruction
$results = $conn->query($query);
is always executed, regardless of whether isset returns true or not.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
}
$results = $conn->query($query);
So if only one field has not been filled out correctly, the error is always the same :
PHP Warning: mysqli::query(): Empty query in ....
This makes it difficult to determine where the fault really comes from.
Place the curly bracket } behind database logic.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
....
}
}
?>
create a short test program to test only the database. Set only really necessary data fields in the query
test.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$Kohderyhmä = "KohderyTest"; // replace with really existing values
$query = "SELECT * FROM `tietokanta` WHERE Kohderyhmä='".$Kohderyhmä."' ";
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
$results->free();
?>
Add hardcoded variables $Näytön_aste = "reallyExistingValue"; , add query data field for data field and watch when it starts to stutter.
Also we can not see your function get_post()
If you mean the Wordpress function get_post(), your call to the function is wrong.
I can well imagine that the failure from the function get_post() comes.
And you always false or empty values assigns.
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
assign it direct.
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
...)
{
$Kohderyhmä = $post['Kohderyhmä'];
...
Also you are using all select fields from the <form>, in the query.
4 Select's with 8,6,6,6 options means
8x6x6x6 == 1728
1728 possibilities are you shure you have one datarecord where all values matches.
WHERE Ko...='$Ko...' AND `Näy...`='$Näy...' AND `Vai...`='$Vai...' AND `Käy...`='$Käy...'";
WHERE All four Datafields must match to get a result !!!!!!!!!!!!!
You have to find a combination where all four values simultaneously exist.
UPDATE
OP new question :
If you want empty or some named values stop searching for a value in
database.
required every single variable to be found in the database which it
didn't find because I couldn't set the variable and there is no value
for "Kaikki" in the database, the word "Kaikki" means all choices
below that choice in the HTML form and for that I need some PHP
Here comes the new test.php
1) don't do $post['Näytön aste']; In the form the name is
<select name="Näytön aste" style="...">.
This will translated by submit to
$post['Näytön_aste']; look at the underscore _
This must be done with all select name with spaces in the name !!
2) That was the reason why you get not all $_POST[....] values !
OK ?
3) replace in your form
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
with
<form action="testNew.php" method="POST">
testNew.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
isset($post['Näytön_aste']) &&
isset($post['Vaikutusten_vahvuus']) &&
isset($post['Käyttökelpoisuus']))
{
$Kohderyhmä = $post['Kohderyhmä'];
$Näytön_aste = $post['Näytön_aste'];
$Vaikutusten_vahvuus = $post['Vaikutusten_vahvuus'];
$Käyttökelpoisuus = $post['Käyttökelpoisuus'];
} else { die ("No valid values"); }
$count = 0;
$and = "";
$query = "";
if (!empty($Kohderyhmä) && $Kohderyhmä !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Kohderyhmä`= '".$Kohderyhmä."'";
}
if (!empty($Näytön_aste) && $Näytön_aste !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Näytön aste`= '".$Näytön_aste."'";
}
if (!empty($Vaikutusten_vahvuus) && $Vaikutusten_vahvuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Vaikutusten vahvuus`= '".$Vaikutusten_vahvuus."'";
}
if (!empty($Käyttökelpoisuus) && $Käyttökelpoisuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Käyttökelpoisuus: luokka`= '".$Käyttökelpoisuus."'";
}
if ($count > 0) {
$query = "SELECT * FROM `tietokanta` WHERE ".$query;
} else {
$query = "SELECT * FROM `tietokanta`";
}
echo $query;
if ($results = $conn->query($query)) {
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
} else {
echo "with your choices no records were found";
}
$results->free();
?>
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='{$Kohderyhmä}' AND `Näytön aste`='{$Näytön_aste}' AND `Vaikutusten vahvuus`='{$Vaikutusten_vahvuus}' AND `Käyttökelpoisuus: luokka`='{$Käyttökelpoisuus}'";
Replace your query with this, and try.
:)
I'm new here and I'm very new with php.
I am trying to make a search form with:
a dropdown list with two items: category and location;
a text field;
a search button.
It should work like this:
When "category" is selected, you enter a text and it will be searched only into categories.
When "location" is selected, your term will be searched among countries, states, zip codes.
I have a table with columns: id, name, category, country, zipcode, state.
Could somebody help me to understand why it doesn't display any results?
Here is my code:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
// retrieving search value we sent using get
$research = $_GET['research'];
// check if it has been sent, then it is ok
if ( $research == 'ok' ) {
// retrieving search value we sent using post
$search = $_POST['search'];
// check if the field has been filled
if ( $search == TRUE && $search != "" ) {
// character lenght more than 3
if ( strlen($search) >= 3 ) {
$search = mysql_escape_string(stripslashes($search));
}
if(isset($_POST['value'])) {
if($_POST['value'] == 'category') {
// query to get all categories
$query = "SELECT * FROM table_name WHERE category='$search'";
}
elseif($_POST['value'] == 'location') {
// query to get all country/state/zipcode records
$query = "SELECT * FROM table_name WHERE country='$search' OR zip_code='$search' OR state='$search'";
} else {
// query to get all records
$query = "SELECT * FROM table_name";
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}
}
}
?>
Thank you very much for your help.
You need to understand how to use <select> with php.
if you have this form:
<form method='post'>
<select name='example'>
<option value='e1'>example1</option>
<option value='e2'>example2</option>
</select>
</form>
You need to print it like that:
echo $_POST['example'];
In case the user selcted example1, the value will be e1.
In case the user selcted example2, the value will be e2.
You are using in your script $_POST['value']. It's just dosen't exist.
Try this, instead:
HTML FORM:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
FORM PROCESSING:
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
/*********************************************/
/***WHY DO YOU NEED THIS RESEARCH VARIABLE?***/
/*****WHAT IS ITS PURPOSE IN THIS SCRIPT?*****/
/*********************************************/
//GET CLEAN VERSIONS OF ALL NECESSARY VARIABLES:
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM table_name 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 == "location"){
$query .= " country LIKE '%" . $search . "%' OR zip_code LIKE '%" . $search . "%' OR state LIKE '%" . $search . "%'";
}
}else{
$query .= "1";
}
$sql = mysql_query($query);
//HERE AGAIN WAS AN ERROR... YOU PASSED mysql_fetch_array A STRING $query INSTEAD OF A RESOURCE: $sql
while ($row = mysql_fetch_array($sql)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}
I am using PHP to call the database to print 3 different dropdown menus. That works. My problem is calling the function and passing the dropdown selections into the function and displaying the records after the submit button is pressed. The function is a build query taking into account if only 1 of the dropwdowns are selected or all 3.
The function is currently in the same page as the the form.
Here is the form:
<form action="edit.php" method="POST">
<select>
<?php $getGroup = mysql_query("SELECT DISTINCT resgroup FROM restable ORDER BY resgroup");
while($viewAllGroups = mysql_fetch_array($getGroup)){
?>
<option id="<?php echo $viewAllGroups['resgroup']; ?>"><?php echo $viewAllGroups['resgroup']; ?></option><?php } ?>
</select>
<select>
<?php $getType = mysql_query("SELECT DISTINCT restype FROM restable ORDER BY restype");
while($viewAllTypes = mysql_fetch_array($getType)){
?>
<option id="<?php echo $viewAllTypes['restype']; ?>"><?php echo $viewAllTypes['restype']; ?></option><?php } ?>
</select>
<select>
<?php $getService = mysql_query("SELECT DISTINCT service FROM restable ORDER BY service");
while($viewAllServices = mysql_fetch_array($getService)){
?>
<option id="<?php echo $viewAllServices['service']; ?>"><?php echo $viewAllServices['service']; ?></option><?php } ?>
</select>
<input type="submit" class="btn btn-primary" value="Filter" />
</form>
Here is the function:
<?php
function displayrecords(){
$groups = $_POST['resgroup'];
$type = $_POST['restype'];
$service = $_POST['service'];
if($groups != ""){
$where[] = " `resgroup` = '".mysql_real_escape_string($group)."'";
}
if($type != ""){
$where[] = " `restype` = '".mysql_real_escape_string($type)."'";
}
if($service != ""){
$where[] = " `service` = '".mysql_real_escape_string($service)."'";
}
$sql_json = "SELECT * FROM mytable WHERE $where_clause ORDER BY id DESC";
}
?>
Then I try to display the function.
<?php displayrecords(); ?>
I am not getting an error, however, once the submit button clicked, the dropdown menu's clear out, and it doesn't return anything. I know I'm missing a lot. I would appreciate any help.
Thank you in advance.
First of all please provide name to each select element. Again in the the edit.php file access the values of post array by that name.
Now I am giving an example for it.
HTML part:
<select name='select1' >
<option value='1'>Value</option>
<option value='1'>Value</option>
</select>
Now in edit.php you can access the value of selected element of selectbox select1
as $_POST['select1'];
You are adding an Array into the string, which will only result in "SELECT * FROM mytable WHERE Array() ORDER BY id DESC"; or something similar.
Try to add this befor your $sql_json = "...line:
$where = implode(" AND ", $where);
This should add restype=value AND service=value etc to your string.
Additionally, you are referencing to $group instead of $groups in your if($groups != "") clause.
Also, you have to give your select tags a name to be able to reference them in $_POST:
<select name="restype">
You need to alter your PHP because the sql statement is looking for a variable $where_clause and I don't see it defined in your code.
You can rewrite the building of the where clause
<?php
function displayrecords(){
$groups = $_POST['resgroup'];
$type = $_POST['restype'];
$service = $_POST['service'];
$where = "";
if($groups != ""){
$where = " `resgroup` = '".mysql_real_escape_string($group)."'";
}
if($type != ""){
if( $where != "" ) $where .= " AND ";
$where .= " `restype` = '".mysql_real_escape_string($type)."'";
}
if($service != ""){
if( $where != "" ) $where .= " AND ";
$where .= " `service` = '".mysql_real_escape_string($service)."'";
}
$sql_json = "SELECT * FROM mytable WHERE $where ORDER BY id DESC";
}
?>
From a dropdown menu a user can choose: view all, athletic, dress, or sandals. I am creating a function that if the user chooses athletic--only the Product Type 'Athletic', only athletic items from the database will be shown.
Right now, because how my code is written, if the user selects 'Athletic' they will see athletic items, but also all other products in the database because the function showAllProducts was called.
I'm not sure how to write, that if a user selects a specific product type, only that product type will be shown.
if (isset($_SESSION['valid_user']))
{
//echo "I am in the if statement of the session";
echo 'You are logged in as: '.$_SESSION['valid_user'].' <br />';
showAllProducts();
} else {
echo "I am not setting the session variable";
//die;
}
$userCat = getUserCategory();
orderByCategory($userCat);
//function athleticCategory ---------------------------------------------
function athleticCategory() {
echo "I am in the athletic function" . "<br/>";
$con = getConnection();
$sqlQuery = "SELECT * from Products
WHERE ProductType='Athletic'";
// Execute Query -----------------------------
$result = mysqli_query($con, $sqlQuery);
if(!$result) {
echo "Cannot do query" . "<br/>";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
echo "Query works" . "<br/>";
} else {
echo "Query doesn't work" ."<br/>";
}
// Display Results -----------------------------
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc ($result);
// print_r($row);
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Image']).'" />';
echo "Price: " . stripslashes($row['Price']);
}
}
Dropdown Menu
<form action="register_script.php" name="frm" method="post">
<select name="category" id="category">
<option value="viewall">View All</option>
<option value="dress">Dress</option>
<option value="athletic">Athletic</option>
<option value="sandals">Sandals</option>
</select>
<input type="submit" value="Go" />
</form>
Edited Code:
$sqlQuery = "SELECT * from Products";
if($pUserCat == "athletic") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='athletic'";
} elseif ($pUserCat == "dress") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='dress'";
} elseif ($pUserCat == "sandals") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='sandals'";
} elseif ($pUserCat == "viewall") {
$sqlQuery = "SELECT * from Products";
}
make a function , that accept one parameter ie category name and use default hint as 0
function categoryList($cat=false){
if($cat)
$sqlQuery = "SELECT * from Products
WHERE ProductType={$cat}";
else
$sqlQuery = "SELECT * from Products";
//do other stuff of Reading option
}
Set your 'View All' form option like this:
<option value="">View All</option>
You can use it as it is.
if (isset($_POST['category']))
$category = $_POST['category'];
$sqlQuery = "SELECT * from Products";
if ( ! empty($category)) {
if (get_magic_quotes_gpc()) {
$category = stripslashes($category);
}
if ( ! is_numeric($category)) {
$category = "'" . mysql_real_escape_string($category) . "'";
}
$sqlQuery .= " WHERE ProductType='{$category}'";
}
It has basic security features so people can't inject malicious SQL into your script.
If you call that function without any category, it will be assumed you want to show all values.
You dont need to check if for each and every single case and then write the sqlQuery according to that, as long as you use the same <option value="xxx"> as the categories are called in your db.