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";
}
?>
Related
I use some filters to display items. But my problem is that when I click a new filter after I clicked an old one, the old one will be removed.
<form id="filters" method="post">
<select name="genre" onchange="this.form.submit()">
<option value="">Genre</option>
<?php
$query = 'SELECT * FROM `imslp_genre` WHERE 1';
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$thisGenre = $row['genre'];
echo "<option value='$thisGenre'>$thisGenre</option>";
}
}
?>
</select>
<select name="instrument" onchange="this.form.submit()">
<option value="">Instrument</option>
<?php
$query = 'SELECT * FROM `imslp_instruments` WHERE 1';
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$thisInstrument = $row['instruments'];
echo "<option value='$thisInstrument'>$thisInstrument</option>";
}
}
?>
</select>
</form>
$query =
'SELECT `sheets_title`,`sheets_genre_ID`, `sheets_instrument1`,`sheets_instrument2`, `sheets_difficulty`, `sheets_img`, `sheets_xml`, `sheets_id`, `difficulty`, `genre`, `arrangement`, `composers`, `instruments`, `instruments2`, `instruments3`, `instruments4`, `instruments5` FROM `imslp_sheets`,`imslp_genre`, `imslp_difficulty`, `imslp_arrangements`, `imslp_composers`, `imslp_instruments`, `imslp_instruments2`, `imslp_instruments3`, `imslp_instruments4`, `imslp_instruments5` WHERE `sheets_genre_ID`=`genre_ID` AND `sheets_difficulty`=`difficulty_ID` AND `sheets_arrangement_ID`=`arrangement_ID` AND`sheets_composer_ID`=`composers_ID` AND `sheets_instrument1`=`instruments_ID` AND `sheets_instrument2`=`instruments2_ID` AND `sheets_instrument3`=`instruments3_ID`AND `sheets_instrument4`=`instruments4_ID`AND `sheets_instrument5`=`instruments5_ID`';
$genre = filter_input(
INPUT_POST,
'genre',
FILTER_SANITIZE_SPECIAL_CHARS
);
$instrument = filter_input(
INPUT_POST,
'instrument',
FILTER_SANITIZE_SPECIAL_CHARS
);
Down here it checks if the filter isn't empty so I guess there should be changed something over here but I can't fight the right solution to remember the previous used filter.
if (!empty($genre)) {
$query .= " AND `genre` = '$genre'";
}
if (!empty($instrument)) {
$query .= " AND `instruments` = '$instrument'";
}
Basicly you have to do something like this:
echo "<option value='$thisGenre' "
.($thisGenre==$genre?'selected':'')
.">$thisGenre</option>";
This will select the option again, when the page is reloaded after submit.
See: https://www.w3schools.com/tags/att_option_selected.asp
i have a dependent drop-down list which composition is being populated depending on KNITTYPE. But when i try to order the composition i can not get any result, it doesnt work . what am i doing wrong ?
my second question is : how can i eliminate the repeat of the same composition results
i know they belong to different rows but i want to merge them so for eaxmple when i select 100%COTTON i want to bring all 100%COTTON results , rightnow its bringing 100% cotton for each KNITTYPE SELECTED ?
<?php
require_once 'dbconnect.php';
if(!empty($_REQUEST["KNITTYPE_id"])) {
$query ="SELECT COMPOSITION FROM egearge3 WHERE KNITTYPE =" . "'" . mysqli_escape_string($conn, $_POST["KNITTYPE_id"] ) ."' AND ORDER COMPOSITION BY ASC" ;
$result = mysqli_query($conn, $query);
?>
<option value="">Select COMPOSITION</option>
<?php
while($row2=mysqli_fetch_assoc($result)){
//var_dump($row2);
if($bul2[$row2['COMPOSITION']] != true && $row2['COMPOSITION'] != 'COMPOSITION' || 1) { ?>
<option value="<?php echo $row2['COMPOSITION']; ?>"><?php echo $row2['COMPOSITION']; ?> </option>
<?php
$bul2[$row2['COMPOSITION']] = true;
}
}
}
?>
Your MYSQL query statement is not in the right way
if(!empty($_REQUEST["KNITTYPE_id"])) {
$query ="SELECT COMPOSITION FROM egearge3 WHERE KNITTYPE =" . "'" . mysqli_escape_string($conn, $_POST["KNITTYPE_id"] ) ."' ORDER BY COMPOSITION ASC LIMIT 1" ;
$result = mysqli_query($conn, $query);
?>
<option value="">Select COMPOSITION</option>
<?php
while($row2=mysqli_fetch_assoc($result)){
//var_dump($row2);
if($bul2[$row2['COMPOSITION']] != true && $row2['COMPOSITION'] != 'COMPOSITION' || 1) { ?>
<option value="<?php echo $row2['COMPOSITION']; ?>"><?php echo $row2['COMPOSITION']; ?> </option>
<?php
$bul2[$row2['COMPOSITION']] = true;
}
}
}
?>
this worked for me i guess
<?php
require_once 'dbconnect.php';
if(!empty($_REQUEST["KNITTYPE_id"])) {
$query ="SELECT COMPOSITION FROM egearge3 WHERE KNITTYPE =" . "'" . mysqli_escape_string($conn, $_POST["KNITTYPE_id"] ) ."' GROUP BY COMPOSITION " ;
$result = mysqli_query($conn, $query);
?>
<option value="">Select COMPOSITION</option>
<?php
while($row2=mysqli_fetch_assoc($result)){
//var_dump($row2);
if($bul2[$row2['COMPOSITION']] != true && $row2['COMPOSITION'] != 'COMPOSITION' || 1) { ?>
<option value="<?php echo $row2['COMPOSITION']; ?>"><?php echo $row2['COMPOSITION']; ?> </option>
<?php
$bul2[$row2['COMPOSITION']] = true;
}
}
}
?>
AND ORDER COMPOSITION BY ASC
That is not valid.
You don't need a AND before ORDER and the correct syntax is ORDER BY X, and not ORDER X BY
ORDER BY COMPOSITION ASC
See DISTINCT to remove duplicate entries from the result
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!
<input type="checkbox" name="average" value="average" <? if (get_option('average') == 'average'){ echo 'checked="checked"';} ?>>Average
<input type="checkbox" name="petite" value="petite" <? if (get_option('petite') == 'petite'){ echo 'checked="checked"';} ?>>Petite
if ( get_option('average') == 'average' ): // choose category
$average = "AND build = '".get_option('average')."'";
endif;
if ( get_option('petite') == 'petite' ): // choose category
$petite = "OR build = '".get_option('petite')."'";
endif;
$qry = mysql_query("SELECT performerid,pic0 FROM ".$table." WHERE **$average $petite** ORDER BY RAND() LIMIT 20");
How can i make this code work? I need the sql query to work if $average is selected, is both $average and $petite are selected, or just $petite is selected?
TY!
you may use something like this:
$selectedCategories = array();
foreach(array('petite', 'average', 'athletic') as $category)
{
if (get_option($category) == $category)
{
$selectedCategories[] = $category;
}
}
$qry = mysql_query(
"SELECT performerid,pic0
FROM ".$table."
WHERE build IN('" . implode("', '", $selectedCategories) . "')
ORDER BY RAND() LIMIT 20;");
Note: this won't work if you select no category.
you need to use php function isset();
if(isset($_POST)){ //checks if post is set
if(isset($)POST['average']) && !isset($_POST['petite'])){
//do staff only average is set
}
elseif(isset($_POST['petite']) && !isset($_POST['average'])){
//do staff only petite is set
}
elseif(isset($_POST['average'] && isset($_POST['average']))){
//do staff both is set
}
}
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.