Order by based on user selection - php

I have a search box which a user can search their favorite cases. I have ordered the search results by date, but I want to make it optional for a user and they can choose it by themselves:
$orders = array("date","price"); //field names
$key = array_search($_GET['sort'],$orders)); // see if we have such a name
$orderby = $orders[$key]; //if not, first one will be set automatically. smart enuf :)
$quer = "SELECT*FROM ".$db_table." WHERE
`case`=
'apartment'
AND `field`=
'sell'
ORDER BY
$orderby";
$query=mysqli_query($connect,$quer)
or die(mysqli_error());
?>
<?php while($row = mysqli_fetch_array($query)):
echo "price ";
echo "address ";
//to simplify the code I do not write the rest
?>
<?php endwhile;?>
For example, order by date or price or other things. How can I do it?
Users can get values from dropdownlist:
<select>
<option value="date">order by date</option>
<option value="price">order by price</option>
</select>

Here one example of have you can get this by allowing user to choose order by what and even in whether ASC/DESC (this is also immune to MySQL injections because of set code values). You can remove checkbox if not needed but then don't forget to remove that part in query too:
if (!empty($_POST['dropdownOption']))
{
$orderBy = ($_POST['orderValue'] == "date") ? "date" : "price";
$orderType = (!empty($_POST['orderType'])) ? "DESC" : "ASC";
$quer = "SELECT * FROM TABLE WHERE `case` = 'apartment' AND `field` = 'sell' ORDER BY ".$orderBy." ".$orderType."";
$query = mysqli_query($connect, $quer) or die(mysqli_error());
}
?>
<form method="post" action="">
<select name="orderValue">
<option value="date">order by date</option>
<option value="price">order by price</option>
</select><br>
<input type="checkbox" name="orderType" value="1">In descending order?</input><br>
<input type="submit" name="dropdownOption" value="Apply">
</form>
Note that I gave this as a form (because I'm not informed how your website looks like and I don't know if you're Ajax or something else. If you're Ajax, then you need to make small changes, actually). With the help of CSS, you can achieve this as if it is just a select menu.

Related

Taking a value from an array and storing it into a variable for a SQL search

Perhaps there may be an easier way to do this however, I need the project to select a patient from the drop down menu. Then when the dropdown menu has got a value, the text field needs to take the NHS number from that drop down menu (array) so that it can be posted elsewhere.
<select name="patient" class="textbox" required>
<option value="">Select a patient</option>
<?php
include 'dbconnection.php';
$sql = "SELECT * FROM clients ORDER by firstname ASC";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row["firstname"]." ".$row["lastname"]; ?>">
<?php echo $row["firstname"]." ".$row["lastname"] .", ".$row["addressl1"].", ".$row["addressl2"].", ".$row["county"].", ".$row["postcode"].", ".$row["nhsnum"]; ?></option>
<?php
$nhs = $row['nhsnum'];
}
?>
</select>
<?php
$sql = "SELECT * FROM clients WHERE nhsnum = $nhs ";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<input type="text" placeholder="NHS number" readonly value=" <?php echo $row["nhsnum"]; ?>">
<?php
}
?>
As you may see, I have created dummy variables of $nhs however its a static variable and doesnt change upon user selection from the drop down list. Can anyone explain how I can merge the two together.
DB setup
i think you should declare the $nhs outside the while loop
Use AJAX, as already suggested, or a form submit button. Your second query should be where your AJAX or submitted form goes. Use $_GET or $_POST, if you are using get or post method, to intercept the option value. Assign that value to your $nhs, then use as you have.
Set the option value to the $nhs value you want, not the person’s name. Example using $_POST
if(isset($_POST['patient'])){
$nhs=$_POST['patient'];
}else{
// whatever code you want to handle a non-submitted value.
}
Add additional code to prevent SQL injection.

How to write the SQL query for a search having to consider several values using php?

On my page, I have text boxes and drop down lists.
All the values are stored in arrays.
I want to fetch values of year from the database vehicles.
Below shows the html code.
<form name="frm_vehicles" action="processinput.php" method ="post">
Enter year of vehicle
<input type="text" name="year[]" >
<select name="choice[]">
<option value="cars" selected="selected">Cars</option>
<option value="lorry">Lorry</option>
</select>
<select name="query[]">
<option value="and" selected="selected">AND</option>
<option value="or">OR</option>
<option value="not">NOT</option>
</select>
<br>
<input type="text" name="year[]">
<br>
<select name="choice[]">
<option value="cars" selected="selected">Cars</option>
<option value="lorry">Lorry</option>
</select>
<div id="disp"></div>
<input type="button" name="addRow" onclick= "addRow()">
<input type="button" type="submit" name="search" value="Search">
</form>
On clicking the button addRow, a javasccript function is called and another row is added. The elemets below are added.
<input type="text" name="year[]" >
<select name="choice[]">
<option value="cars" selected="selected">Cars</option>
<option value="lorry">Lorry</option>
</select>
Thus, we can see that the fields are dynamically added.
When all fields have been selected, the input are sent to the processinput.php file.
In this file, SQL statements are written.
What should happen is a statement should be executed based on the user's input.
Cars and Lorry are two different tables
The and/or/not are used as joins.
If 'and' is selected, both value of the previous year entered and the value after should match.
If 'or' is selected, only one value may match.
If 'not' is selected, the values after the 'not' is not selected.
So what need to be done is to write a SQL statement to take the values and perform the search.
For example
I add a third row.
i entered 2006 in first text box and selected table 'cars' and 'and'
in the 2nd row, i entered year selected table 'lorry' and 'not'
in the third row i entered table 'year' and 'cars'
$year=$_POST['year'], $choice=$_POST['choice'],
$query=$_POST['query']
Can someone guide me how to write a single sql statement.
How will i mention the $year, $choice and $query in my sql statements?
Should i use a loop ?
Choice will have either tables cars or lorries.
Cars table; columns make, model, year
Toyota.nze.2006
nissan.march.2010
Lorry table; columns make, model, year
ford.hhh.2006
toyota.gggg.2010
For all 2015 bmw, audio, mercedes benz
SELECT * FROM table WHERE year = 2015 AND (choice = 'ford' OR choice = 'audio' OR choice = 'mercedes benz')
Use " and interpolate variables with {$variable} to define strings in PHP.
You will need to build up the WHERE clause using a loop. I would recommend that you look at binding values to prevent SQL injection.
In effect, you will need a query which is doing something like
$baseQuery = "SELECT *
FROM <table>
WHERE (`year` = $year[0] and `choice` = $choice[0])";
as a base query
You'll then probably need to ascertain how many additional rows there are, and if there are more than one then add to your base query so you could do something like;
$additional = '';
if (count($year) > 1) {
foreach($year as $key=>$y) {
if($key > 0) {
$additional .= $query[0] . "(`year` = $year[$key] and `choice` = $choice[$key])";
}
}
}
If you stick this above the $baseQuery and then append the $additional to the base query;
$additional = '';
if (count($year) > 1) {
foreach($year as $key=>$y) {
if($key > 0) {
$additional .= $query[0] . "(`year` = $year[$key] and `choice` = $choice[$key])";
}
}
}
$baseQuery = "SELECT *
FROM <table>
WHERE (`year` = $year[0] and `choice` = $choice[0]) " . $additional;

How to filter based on two arguments from php, in a SQL database

I have a MySQL database, and the table I need to work with has 9 columns of information. My goal is to be able to filter, based on two arguments. For instance, the table is about students so it has data for first name, last name, id, course they are signed up for, status, occupation age and another 2 fields that are not that important. I need to be able to filter, based on the student's status and/or the course.
So far, I managed to get the php work done, with a form and a select tag, to filter based on status, but I have no idea how to add the second part. The done thing should be able to filter, based on status only, based on course only, or based on the selected status and course. The code looks like this:
if (isset($_POST['filter'])) {
$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
$q .= " WHERE status = '$search_term'";
}
echo $q;
<form method="POST" action="index.php">
<select name="filter_status" >
<option value="confirmed">confirmed</option>
<option value="declined">declined</option>
<option value="rejected">rejected</option>
<option value="pending">pending</option>
<option value="unconfirmed">unconfirmed</option>
</select>
<input type="submit" name="filter">
</form>
This works correctly, I have it a second time for the second criteria, but they don't work together.
try to change,
$q .= " WHERE status = '$search_term'";
to
$q .= " WHERE CONCAT_WS(',',status,course) like %'$search_term'%";
you can add as many columns after course.
$filter_status = $_POST['filter_status'];
$course = $_POST['course'];
$where = 'WHERE 1';
$where .= $filter_status ? " AND status = {$filter_status}" : '';
$where .= $course ? " AND course = {$course}" : '';
Did you mean this? when user select course and filter_status use this two conditions, on the other hand use one of conditions which is being selected.
The WHERE 1 will always be TRUE, so it can be followed by AND statements
Use the term AND or OR in your query after WHERE
WHERE status = '$search_term' AND course = '$something'
Thank you all for your input. It helped nudge me in the right direction. The code that ended up doing what I needed is as follows. It's not very elegant, but it does the job well:
$q = "SELECT *
FROM students";
if (isset($_POST['filter'])) {
if ($_POST['filter_status'] == null) {
$search_term2 = mysqli_real_escape_string($conn, $_POST['filter_course']);
$q .= " WHERE course = '$search_term2'";
} elseif ($_POST['filter_course'] == null) {
$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
$q .= " WHERE status = '$search_term'";
} else {
$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
$search_term2 = mysqli_real_escape_string($conn, $_POST['filter_course']);
$q .= " WHERE status = '$search_term' AND course = '$search_term2'";
}
}
And the form:
<form method="POST" action="index.php">
<select name="filter_status" >
<option value= ""></option>
<option value="confirmed">confirmed</option>
<option value="declined">declined</option>
<option value="rejected">rejected</option>
<option value="pending">pending</option>
<option value="unconfirmed">unconfirmed</option>
</select>
<select name="filter_course">
<option value= ""></option>
<option value="php">php</option>
<option value="java">java</option>
</select>
<input type="submit" name="filter">
</form>

php: change value of variable based on dropdown list

Learning PHP and having an issue that I can't figure out. I have read that PHP only has scope for functions, so I'm not sure why my switch statement isn't changing the value of variables.
Goal: to change the mysql SELECT statement based on user selection of drop-down.
Form:
<form action="contacts_show.php" method="POST">
<select name="grade" id="grade">
<option value="all">All Levels</option>
<option value="elementary">Elementary</option>
<option value="middle">Middle</option>
<option value="senior">Senior</option>
<input type="submit" name="browse" id="browse" value="Browse" />
</form>
PHP (edited to shorten code):
$levelSelected = $_POST['grade'];
if ($levelSelected == "all") {
$querySelect = "SELECT * FROM teachers ORDER BY school ASC";
} else {
$querySelect = "SELECT * FROM teachers WHERE school LIKE %$levelSelected% ORDER BY school ASC";
}
$query = $querySelect;
$result = mysqli_query($connection, $query);
confirm_query($result);
the confirm_query function, if needed:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
When "All Levels" from drop-down is selected, code runs as expected. When any other option is selected, my confirm_query function states that the query fails.
I'm not sure why the variable's values are not switching.
To elaborate on my comment:
Change LIKE %elementary% to => LIKE '%elementary%' and do the same for the others.
You need to wrap the pattern match in quotes, and as per the manual:
http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like
mysql> SELECT 'David!' LIKE '%D%v%';
mysql> SELECT 10 LIKE '1%';
You're also not checking for DB errors.
Add or die(mysqli_error($connection)) to mysqli_query()
If that still doesn't work, then it's also a scope issue.
Pass the connection to your function, do not make it global.

drop down menu to sort query results on a php page

I have a simple list-type php page, which lists items according to a mysql query, like:
mysql_select_db($database_connBHN, $connBHN);
$query_rsMarket = "SELECT * FROM my_items WHERE active=1 ORDER BY name asc";
$rsMarket = mysql_query($query_rsMarket, $connBHN) or die(mysql_error());
$row_rsMarket = mysql_fetch_assoc($rsMarket);
$totalRows_rsMarket = mysql_num_rows($rsMarket);
then the page list these items and their description in separate tables.
Initially this page lists these items in alphabetical order. Now I would like to put a drop down box on the top of the page, where the user could choose another two or three more sorting options, like date, or itemId, etc, which values are stored in the database.
How could I solve this in a simple way, without leaving that page? (i.e. I do not want to create separate pages for each different result set)
No, it's easier to keep this as a single script and just allow for the sorting variable to be switched. For security's sake, it's best to limit the user input to a per-defined set of options in the PHP script:
$sort_options = array('name asc','name desc','dateadded asc','dateadded desc');
if(!isset($_GET['field'])){
$_GET['field'] = 'name';
}
if (!isset($_GET['order'])){
$_GET['order'] = 'asc';
}
$full_query_sort = $_GET['field'].' '.$_GET['order'];
if (!in_array($full_query_sort,$sort_options)){
die('invalid selection');
}
mysql_select_db($database_connBHN, $connBHN);
$query_rsMarket = "SELECT * FROM my_items WHERE active=1 ORDER BY ".$full_query_sort;
$rsMarket = mysql_query($query_rsMarket, $connBHN) or die(mysql_error());
$row_rsMarket = mysql_fetch_assoc($rsMarket);
$totalRows_rsMarket = mysql_num_rows($rsMarket);
Now you can just have the order set with _GET variables: http://example.com/page.php?field=name&order=desc etc. This can be set with javascript (or on form submission) using dropdowns:
<select id='field_select'
name='field'
onchange="window.location='?field='+this.value+'&order='+document.getElementById('order_select').value;">
<option value='name' <?php if(!isset($_GET['field']) || $_GET['field']=='name'){echo "selected";} ?>>Sort by Name</option>
<option value='dateadded' <?php if(isset($_GET['field']) && $_GET['field']=='dateadded'){echo "selected";} ?>>Sort by Date Added</option>
</select>
<select id='order_select'
name='order'
onchange="window.location='?field='+document.getElementById('field_select').value+'&order='+this.value;">
<option value='asc' <?php if(!isset($_GET['order']) || $_GET['order']=='asc'){echo "selected";} ?>>Ascending/option>
<option value='desc' <?php if(isset($_GET['order']) && $_GET['order']=='desc'){echo "selected";} ?>>Decending</option>
</select>

Categories