PHP select filter - php

I have a page with list of persons.
Now I want to filter them with a drop down select.
Here's my code:
<main>
<div class="wrapper">
<div class="team-list">
<h3><?php echo $teamTitle; ?></h3>
<div class="filter">
<label for="filter"><?php echo $specialtiesTitle; ?></label>
<form action="" method="post">
<div class="form-item">
<select name="specialties">
<?php
$query = "SELECT * FROM specialties";
$result = mysqli_query($connection, $query);
echo '<option selected="selected" value="All">'. $filterTitle . '</option>';
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$title = $row['title_'.$lang];
echo '<option value="' . $id . '">' . $title . '</option>';
}
?>
</select>
</div>
<div class="form-item">
<input class="form-submit" type="submit" name="submit" value="<?php echo $filterSubmit; ?>">
</div>
</form>
</div>
<div class="content">
<?php
$query = "SELECT * FROM team";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$image = $row['image'];
$title = $row['title_'.$lang];
echo '<div class="row">';
echo '<div class="image"><img src="/uploads/' . $image . '"></div>';
echo '<a class="title" href="/team-view?id=' . $id . '">' . $title . '</a>';
echo '<a class="more" href="/team-view?id=' . $id . '">' . $teamMore . '</a>';
echo '</div>';
}
?>
</div>
</div>
</div>
</main>
As you can see from the code the first part has the div filter that receives select from the database.
This line:
echo '<option selected="selected" value="All">'. $filterTitle . '</option>';
Is a additional option with value "All" and the other options are getting from the "specialties" table.
The second part is the content that pulls from the "team" table.
I'm relating the categories from "Specialties" table with the "Team" table.
In the Admin area of my Custom CMS, everything is working and when I change the "Specialties" category, it saves successfully in the database.
Right now the page displays all the fields, but I don't have functionality of filtering.
How can I filter the content?
I know that I have to use:
if(isset($_POST['submit'])) {
//the code inside
}
but what query should I use for such filtering?
EDIT:
By filtering I mean, when I have the list content and from top I have a select drop down and search button. So if I select let's say the first value from the options and click on submit, it should display only the content that has the first category value inside.
In the table "Team" I have many fields and these are the connection:
id
specialties_bg
specialties_en
This is the table "Specialties"
id
title_bg
title_en
Title_bg and title_en has all the options values and id is the connection.
The website is multilingual and that's why I have two fields for different languages.

Check the below code. If the form is submitted add a condition to the query.
$query = "SELECT * FROM team";
// declare the variable
// check if the form is submitted and have a valid search value
if(isset($_POST['submit']) && (trim($_POST['specialties'])!='') && (trim($_POST['specialties'])!='ALL')) {
//add the condition
$query.= " WHERE specialties_en='".trim($_POST['specialties'])."'";
}
You can modify condition based on the languages with OR condition.
Always check the user input for sql injections.

Fetching Specific Data From Database :
In order to fetch all data from a table you can do that simply by using SELECT Query in MySQL as :
SELECT * FROM table;
But as now you want to filter the whole data and just get something specific from your database so for that you must should have something unique in order to differentiate the expected data from the whole rest of the data.
TWO WAYS TO DO THAT :
1) Using An Extra Field (Column) In Your Database Table :
You can do that by adding an extra field (column) to your table structure like something which will contain values based on the records in order to put them in a collective based group.
For Instance :
I have a table with alot of records of players now I add a column namely as sport so now I have something unique in order to filter the players.So I can use following SQL SELECT Query to get all those players as:
SELECT * FROM players WHERE sport="sport_name";
2) Filtering Data Through PHP :
If you don't want to get the filtered data from the Database,So you can do the same process in PHP also as:
For Instance :
You already fetched the whole data from the players table and now you want to filter it so you can filter it like this way as :
<?php
//Assuming that $results contains the whole fetched data from table
for ($i=0;$i<=count($results);$i++) {
if ($results[$i]['sport'] == "cricket") {
// Can target any sport located in your database
//You can pretty much do anything you want..!
echo $result[$i]['player_name'];
}
}
?>

Related

Displaying form selected option results from database

Okay, I'm reframing this whole question because the earlier version was a bit convoluted.
Here's the scenario:
I have a MySQL table called "churches."
I have a form with four selects. The options are drawn dynamically from the table, so that users can search on four table columns to find churches that fit the criteria (country, state/province, city, presbytery)
I also have working code to get all the table data to display.
What I haven't figured out is how to use the selected option from the form to filter the results.
My current code is below:
<form action="display0506b.php" method="post">
<select name="country">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT country FROM churches");
$query_display = mysqli_query($link,"SELECT * FROM churches");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['country'] . "</option>";
}
?>
</select>
<select name="state">
<option value=""></option>
<?php
$query = mysqli_query($link, "SELECT DISTINCT state FROM churches WHERE state != ''");
$query_display = mysqli_query($link,"SELECT * FROM churches WHERE state != ''");
while ($row = mysqli_fetch_array($query)){
echo "<option value='" . $row['id']."'>". $row['state'] . "</option>";
}
?>
</select>
<input type="submit" value="Go!">
</form>
<?php
if(isset($_POST['country']))
{
$name = $_POST['country'];
$fetch = "SELECT * FROM churches WHERE id = '".$name."'";
$result = mysqli_query($link,$fetch);
echo '<div class="churchdisplay">
<h4>' .$row['churchname'].'</h4>
<p class="detail">' .$row['detail'].'</p>
<p><b>' .$row['city'].'</b>, ' .$row['state'].' ' .$row['country'].'</p>
<p>' .$row['phone'].'</p>
// etc etc
</div>';
}
else{
echo "<p>Please enter a search query</p>";
}
?>
Note that in the form above, I only have two selects for illustration, but ultimately I will have four, as mentioned; and I am only attempting the country selection at this point to keep things simple. Ultimately, I will need the ability to select any (and preferably all) of the four categories.
As you can see, this code does attempt to "grab" the selected value from the form, but it's not working. I've pondered numerous tutorials and examples, but none of them do exactly what I'm after, and as an extreme PHP novice, I'm stumped.
So the question: how do I tweak this so that I can "grab" the form selection and display the relevant results from my table?
Edit: I am using mysqli syntax, and want to just use PHP and MYSQL (no Ajax etc) if possible.
Well, it looks like I've finally found what I needed here:
display result from dropdown menu only when value from it is selected
Or, I should say, I've got it to work with one select option. Still need to see if I can figure out how to get four working together.

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.

combining output of two querys and displaying information in one list

I currently have this page to select two lots of information and display it to the page it works by outputting two separate lists one list with check boxes to select an item to add to the database and the other list to show the titles that the user currently has but i need to simplify the output if possible to only display one list that has the information for the title on one line with wither no check box or a tick image next to the ones that the user is subscribed to or a cross next to the ones they are not.
i have added the code below and commented the query and output
// Check to see if the form has been submitted
if(isset($_POST['submit'])){
// Declare shorthand for the id value if there is $_POST data
$id = $_POST['userId'];
// Connect to the database
$objects->connect();
// Create a variable full of the posted array sub
$list = $_POST['sub'];
// for each loop to insert each value into the database with the selected users informtion
foreach ($list as $value) {
// The query to run
$listQuery='INSERT IGNORE INTO tbl_list (`userId`, `subId`) VALUES (\'' . $id . '\', \'' . $value . '\')';
// Run the query
$objects->query($listQuery);
}
}
else{
// Filter all of the $_GET data
$objects->filterEverything($_GET);
// Declare shorthand for the id value if there is $_GET data
$id = $objects->clean['userId'];
}
//////////////////////////////////////////////////////////////////////////////////////////
Here is the first query to check if the user is subscribed to a title
//////////////////////////////////////////////////////////////////////////////////////////
// This section will select any existing titles that the selected client is subbed to
// Connect to the database
$objects->connect();
// The query to select the info for the clients current subb titles
$exist = 'SELECT a.`subId`, a.`userId`, b.`subTitle`, b.`subId` FROM `tbl_list`a, `tbl_subs`b WHERE a.`subId` = b.`subId` AND a.`userId` =' . $id;
// Create a variable and set it to the query
$result = $objects->query($exist);
// Consctuct the output
$existOutput = '';
// Loop through the results and create the output with the count
while($result = $objects->result->fetch_array(MYSQLI_BOTH)){
$existOutput .= '<p>' . $result['subId'] . '' . $result['subTitle'] . '</p>';
}
// Select the chosen users information from the database
// Connect to the database
$objects->connect();
// query the database
$query = 'SELECT `userId`,
`firstName`,
`lastName`
FROM `tbl_user`
WHERE `userId` =' . $id;
// Run the query
$objects->query($query);
//Store the results returned from the database
$row = $objects->result->fetch_array(MYSQLI_BOTH);
// Create the users output
$output = '' . $row['firstName'] . ' ' . $row['lastName'] . '';
//////////////////////////////////////////////////////////////////////////////////////////
Here is the second query to create a list of titles with check boxes to add to the users list Note the list still displays the titles that the user is subscribed to
//////////////////////////////////////////////////////////////////////////////////////////
// This section selects the selected users name
// Connect to the database
$objects->connect();
// Query for the database
$selectionQuery = 'SELECT `subId`, `subTitle` FROM `tbl_subs`';
// Run the query
$objects->query($selectionQuery);
// Create the output
$subOutput = '';
$subOutput .= $objects->openForm();
while($row = $objects->result->fetch_array(MYSQLI_BOTH)){
$subOutput .= '<input type="checkbox" " name="sub[]" value="' . $row['subId'] . '" />' . $row['subTitle'] . '<br />';
}
$subOutput .= $objects->makeInput('userId','hidden','none');
$subOutput .= $objects->makeSubmitButton('submit','Edit','submit');
$subOutput .= $objects->closeForm();
}
else{
// If the user is not logged in then redirect to the login page
header("Location:index.php");
}
//Include the header for the page
include_once '../includes/header.php'
?>
<!-- The Body section starts here -->
<div id="body">
<div class="bodyBox">
<!-- The left side of the body -->
<div class="bodyLeft left">
<div class="cmsContainer">
<h2>Manage Subs</h2>
<div class="cmsMargin">
<p>Manage the subscriptions for <?php echo $output; ?></p>
<?php echo $subOutput; ?>
<?php echo $listTest; ?>
<p><a class="link left" href="index.php">Control Panel</a></p>
<p><?php echo $existOutput; ?></p>
You probably need an Outer Join:
SELECT a.`subId`, a.`userId`, b.`subTitle`, b.`subId`,
CASE -- check if there was a matching b.`subId`
WHEN b.`subId` IS NOT NULL THEN 'x' ELSE ' ' END
END
FROM `tbl_list`a LEFT JOIN `tbl_subs`b
ON a.`subId` = b.`subId`
WHERE a.`userId` =' . $id

Setting combo box to value dynamically retrieved from database in PHP

I have a task that I need to retrieve data from the database and set it in the Combo Box. Fortunately, I have done it.
Now, I have a Search Button which retrieves the data relevant in these text and combo boxes. My Issue is, After I click Search Button all my combo box and text box selected values become empty. How can I set those same data after clicking Search button ?
My Code Effort is,
<?php
$sql="select cat_id,cat_name from disease_category group by cat_id ";
foreach ($dbo->query($sql) as $row){
if(isset($_REQUEST['cat_name'])&&$_REQUEST['cat_name']==$row[cat_name])
{
echo "<option value=$row[cat_id] selected='selected' >$row[cat_name]</option>";
}
Else
{
echo "<option value=$row[cat_id]>$row[cat_name]</option>";
}
}
?>
My SEARCH button code,
<?php
include 'config.php';
if(isset($_REQUEST['SUBMIT']))
{
$cat=$_REQUEST['cat'];
$subcat=$REQUEST['subcat']
$sel=mysql_query("SELECT * from table_name where cat_id like '$cat%' AND sub_id like '$sub_cat%'AND survier like '$survier%' ")
}
It should be pretty simple. I still don't fully understand what you're trying to do. But if all you want is to dynamically populate an options list based on the results of a SQL query.
<?php
$sql = '
SELECT
*
FROM
`my_table`
';
$query = mysql_query($sql) OR die(mysql_error());
print '<select name="dropdown">';
while ($row = mysql_fetch_assoc($query)) {
print '<option value="'. $row['cat_id'] .'"';
if (
isset($_REQUEST['cat_name']) &&
$_REQUEST['cat_name'] == $row['cat_name']
) { print ' selected="selected"'; }
print '>'. $row['cat_name'] .'</option>';
}
print '</select>';
?>
You should be able to modify the SELECT query to fit your needs, and modify content within the while() loop, as well. That should get you going if I understand what you're trying to do.

select id from the select gender dropdown list

I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/

Categories