I want to link searches from a checkbox form together. E.g i have 5 checkboxes (a,b,c,d,e) if i have checked a and b, i want to search depending on what i have searched i.e display two different results.
<form role="form" action="R.php" method="post">
<div class="form-group">
<input type="checkbox" value="a" name="search" />a
<input type="checkbox" value="b" name="search" />b
<input type="checkbox" value="c" name="search" />c
<input type="checkbox" value="d" name="search" />d
<input type="checkbox" value="e" name="search" />e
</div>
<input class="btn btn-default glyphicon-align-right" type="submit" value=">>"/>
</form>
The PHP
<?php $output='';
if(isset($_POST['search'])){
$searchq=$_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$Squery = mysql_query("SELECT * FROM database WHERE Name LIKE '%$searchq%'");
$count = mysql_num_rows ($Squery);
echo "<div id=results><ul class=list-group><div id=qwerty>";
if($count == 0){
$output = 'There was no results!';
}else{
while($row = mysql_fetch_array($Squery)){
$name = $row ['Name'];
$id = $row['ID'];
$category = $row['Category'];
$output .='<div class="container">'.$name.$category.' '.$id.'</div>';
echo "<li>"."<div style=height:95px ><h3 class=text-center style=text-transform:capitalize >".$name.' '."</h3></div>".
"<div>"."<a href=n.php><img src=images/$id.jpg alt=Image /></a>
</div>".
' '.$category.' RESULT!!!!!'.$id."</li>";
}
echo "</div></ul></div>";
}
}
?>
If I understand the question correctly, you would want to be able to search for all results that match the checkboxes that you have checked.
I'm not sure exactly what results you would be looking for, so instead I'll give you a few different options and let you take it from there.
First, in order to pass MORE THAN ONE checkbox to your PHP script, you need to define you checkboxes differently.
<form role="form" action="R.php" method="post">
<div class="form-group">
<input type="checkbox" value="a" name="search[]" />a
<input type="checkbox" value="b" name="search[]" />b
<input type="checkbox" value="c" name="search[]" />c
<input type="checkbox" value="d" name="search[]" />d
<input type="checkbox" value="e" name="search[]" />e
</div>
<input class="btn btn-default glyphicon-align-right" type="submit" value=">>"/>
Notice the brackets after "search" .. name = "search[]". This allows your checkboxes to pass over a COLLECTION of values, instead of just one.
Secondly, on your PHP side.
Once you submit your checkboxes, you will want to get them the same way you currently do:
$searches = $_POST['search'];
$searches will now be an array filled with the values that were checked in your form.
Depending on your desired result, what you do next would look something like this.
Let's take the case that A and B were checked.
If you want to get all results where the word begins with the letter A OR the word begins with the letter B:
<?php
$searches = $_POST['searches'];
$Squery = "SELECT * FROM database";
$Swhere = "";
//add all your individual searches by looping through the checkbox values
foreach($searches as $search){
$Swhere .= " OR name LIKE '%$search' ";
}
//remove the first OR case, because it is not needed for the first search query
$Swhere = ltrim($Swhere, ' OR');
//add your dynamic where statement to your query
$Squery .= $Swhere
$result = mysql_query($Squery);
//...... run the query and get the results the same way you are
By using the foreach function, your can add all the checkboxes you want to your search, but the query on the PHP side will not have to change at all.
On a similar note, in the case of A selected and B selected, if you want to get all words that begin with A, begin with B, OR begin with AB, then your code would be adjusted like so:
<?php
$searches = $_POST['searches'];
//this takes your array of values and combines them into one word.
//your searches variable remains an array, but your stringSearch is now
//a word with the combined values
$stringSearch = implode($searches,'');
$Squery = "SELECT * FROM database";
$Swhere = " name LIKE '%$stringSearch%' ";
//add all your individual searches by looping through the checkbox values
foreach($searches as $search){
$Swhere .= " OR name LIKE '%$search' ";
}
//add your dynamic where statement to your query
$Squery .= $Swhere
$result = mysql_query($Squery);
//...... run the query and get the results the same way you are
Hopefully you can take this example and adjust to what your actual needs are.
One thing to note, is you SHOULD NOT be using mysql_query. It is opening your code up to major SQL injection concerns. I only used it above to display how you would do it with your current code. Look into the mysqli functions
Related
I have the following situation:
I have created a code for a Search box that allows the user to do some advanced search and created a prepared mysql statement. The form target is the same page.
I have also created another form that allows sorting. The form target is the same page.
The problem is that if I search for something and then I sort the data, it gets back to the default query (without the parameters set on the search box) so it sorts the whole data.
They work perfect isolated, but I would love to make them work together and I really can't figure out how.
Here is the PHP code for the Search box and the sorting:
<?php
require 'connect.php';
if(isset($_POST['cauta'])){
$cauta=$_POST['cauta'];}
$clause = " WHERE ";
$query1="SELECT nume, prenume, email, functie, denumire FROM contacte_companii cc LEFT JOIN companii c
ON cc.com_id=c.id";
if(isset($_POST['submit'])){
if(isset($_POST['keyword'])){
foreach($_POST['keyword'] as $c){
if(!empty($c)){
$base_query=$query1 .= $clause." ".$c." LIKE '%".$cauta."%'";//
$clause = " OR ";//Change to OR after 1st WHERE
}
}
}
echo $base_query;
}
else {
$base_query="SELECT nume, prenume, email, functie, denumire FROM contacte_companii cc
LEFT JOIN companii c
ON cc.com_id=c.id";
echo $base_query;
}
?>
if(isset($_POST['ASC'])){
$query = $base_query . " ORDER BY prenume ASC"
;
}
// Descending Order
elseif (isset ($_POST['DESC'])) {
$query = $base_query . " ORDER BY prenume DESC";
}
else {
$query = $base_query;
}
$result=$db->query($query);
// Associative arrays of strings - for each row - stops at NULL;
while($row=$result->fetch_assoc())
{
?>
<tr>
<td><?php echo $row["prenume"]. " " .$row["nume"]; ?></td>
<td><?php echo $row["email"]; ?></td>
<td><?php echo $row["functie"]; ?></td>
<td><?php echo $row["denumire"]; ?></td>
</tr>
<?php
}
$db->close();
?>
Here is the form for the Search box:
<form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<input type="checkbox" name="keyword[]" value="nume" checked> Nume
<input type="checkbox" name="keyword[]" value="prenume" checked> Prenume
<input type="checkbox" name="keyword[]" checked value="email"> Email
<input type="checkbox" name="keyword[]" value="denumire"> Companie
<input type="checkbox" name="keyword[]" value="telefon_b"> Telefon
<input type="checkbox" name="keyword[]" hidden value="telefon_m">
<input type="text" name="cauta">
<input type="submit" name="submit" value="Cauta">
</form>
And here is how the sort button looks like in HTML:
<form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
th>Nume <button class="btn" type="submit" name="ASC" >
<img src="icons\09.png" width="20" height="20" style="margin:3.5px 3px" align="right"/>
</button></th>
</form>
It's not a perfect solution but you could add at the second form as much hidden input and then make your test by keyword
<form action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<input type="hidden" name="keyword[]" value=<? echo $_POST['Num'];?> >
<input type="hidden" name="keyword[]" value=<? echo $_POST['prenume'];?> >
<input type="hidden" name="keyword[]" value=<? echo $_POST['Email'];?> >
<input type="hidden" name="keyword[]" value=<? echo $_POST['Companie'];?> >
<input type="hidden" name="keyword[]" value=<? echo $_POST['Telefon'];?> >
th>Nume <button class="btn" type="submit" name="ASC" >
<img src="icons\09.png" width="20" height="20" style="margin:3.5px 3px" align="right"/>
</button></th>
</form>
First of all if you use a database query class you should use its prepared statements functionality, because otherwise you are vulnerable to SQL injection.
For example if I type in for the last keyword[] something like this "123'; SELECT * FROM users;--". An attacker could exploit this in many ways, as he can write queries that your database will execute because it has no reason to doubt their validity.
Another thing to do is to sanitize the input you get from the forms.
And for the answer to your problem, you can combine the forms and add a checkbox or something to identify if you want to search or to order data. Because I see in your code that have a condition for the $_POST['cauta'].
Or you could combine the forms then you can add this to your query:
if(isset($_POST['cauta'])){
$cauta=$_POST['cauta'];}
$clause = " WHERE ";
$query1="SELECT nume, prenume, email, functie, denumire FROM contacte_companii cc LEFT JOIN companii c
ON cc.com_id=c.id";
if(isset($_POST['submit'])){
if(isset($_POST['keyword'])){
foreach($_POST['keyword'] as $c){
if(!empty($c)){
$base_query=$query1 .= $clause." ".$c." LIKE '%".$cauta."%'";//
$clause = " OR ";//Change to OR after 1st WHERE
}
}
if(isset($_POST['ASC'])){
$base_query .= " ORDER BY prenume ASC";
}
// Descending Order
elseif (isset ($_POST['DESC'])) {
$base_query .= " ORDER BY prenume DESC";
}
}
echo $base_query;
}
The problem is that you are using 2 different forms.
So, when you send any of the forms it only sends the parameters contained in that form, not the ones in the other form, so it will "forget" what the other form sent.
Solutions: (many ways actually, here are some)
Enclose all the parameters in only one form instead of 2, that way it will send always all the information. ** (I think this would be the easiest)
Add the parameters from the search form as hidden fields into the sort form and viceversa.
Use the session or cookie to keep track of the last options used (if you do this you need to consider a way to "clear" the options, like a Clear button that removes everything from the session or cookie)
I've looked through a lot of questions, so forgive me if there is one that may help, but I've not been able to figure this out.
So I have a simple HTML form, that takes the users input for three categories: multiplayer, platform, and genre. This is the html code
<form method="post" action="gamebuddy.php">
<div class="players">
Please select one (or both) of the following: <br>
<input type="checkbox" name="players[]" value="No">Single Player<br>
<input type="checkbox" name="players[]" value="Yes">Multiplayers<br>
</div>
<div class="platform">
Please select your game system(s): <br>
<input type="checkbox" name="platform[]" value="XBOX">Xbox<br>
<input type="checkbox" name="platform[]" value="PS3">PS3<br>
<input type="checkbox" name="platform[]" value="PC">PC<br>
<input type="checkbox" name="platform[]" value="Wii">Wii<br>
</div>
<div class="genre">
Please select the genre(s) of game you would like: <br>
<input type="checkbox" name="genre[]" value="Action" >Action<br>
<input type="checkbox" name="genre[]" value="Casual">Casual<br>
<input type="checkbox" name="genre[]" value="Roleplaying">Role-Playing<br>
<input type="checkbox" name="genre[]" value="Shooter">Shooter<br>
<input type="checkbox" name="genre[]" value="Sports">Sports<br>
</div>
<div class="submit">
<input type="submit">
</div>
And then I have a PHP file that is used when the user clicks submit. Ideally, it takes the form inputs as a variable, and uses the SQLite statement to find the games the user can play based on his choices.
Here's the PHP code:
<div class="displaygames">
Based on your choices, these games seem suitable for you: <br>
<?php
if(!empty($_POST['players'])) {
foreach($_POST['players'] as $players) {
echo $players; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['platform'])) {
foreach($_POST['platform'] as $platform) {
echo $platform; //echoes the value set in the HTML form for each checked checkbox.
//so, if I were to check 1, 3, and 5 it would echo value 1, value 3, value 5.
//in your case, it would echo whatever $row['Report ID'] is equivalent to.
}
}
if(!empty($_POST['genre'])) {
foreach($_POST['genre'] as $genre) {
echo $genre; //echoes the value set in the HTML form for each checked checkbox.
}
}
//This is to connect to the database
$db = new SQLite3('gamebuddy.db');
//Statement that uses variables to create list
$results = $db->query("SELECT * FROM games where multiplayer = '$players' and platform = '$platform' and genre is '$genre'");
//Displays List
while ($row = $results->fetchArray()) {
echo '<ul>';
echo $row['game'];
echo '</ul>';
}
?>
So everything works fine if you put in one answer for each category (for example, the user clicks "No" to multiplayer, "PS3" to platform, and "action" to genre). BUT if the user selects "Action" AND "Role-Playing", for some reason it only takes the last one the user selects, in this instance "role-playing".
So my question is how do I get the statement to show ALL of the games when there are multiple inputs.
Thank you for your help, I will answer any questions there may be, and of course mark the answer as solved if it helps. Thanks!
If u have array in for example $players, u can use implode function and "IN" statement in SQL:
"SELECT * FROM games WHERE multiplayer IN (".implode(",", $players).")"
I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth
I want to have a form that allows the user to choose what data to display from a table through checking the checkboxes. If the user wants only 2 columns to be shown, should only 2 columns be shown. I have my codes, but after I submit, it displays nothing.Here's my code:
<form name="form1" method="post" action="view_emp.php">
<p>Select Option
<input type="checkbox" name="number[]" value="name" />Name
<input type="checkbox" name="number[]" value="hired" />Date Hired
<input type="checkbox" name="number[]" value="basic" />Basic Pay
<input type="checkbox" name="number[]" value="incentives">Incentives
</p>
<input type="submit" name="Submit" value="Submit">
</form>
here's my php:
<?php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('eis', $db) or die (mysql_error());
$employee = array();
foreach ($_POST['number'] as $employee) {
$number = mysql_real_escape_string($number);
$employee[] = "'{$number}'";
}
$sql = "select * from employees where type in (" .implode(", ", $number). ")";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
print $row['name'];
}
?>
i am a beginner in php and i need help from gurus and experts. thank you...
PHP's implode() and explode() functions might come in handy. You can easily turn your POST or GET attribute, 'number', into a comma-separated list by using implode($_POST['number']). This would be easy to store in one MySQL field, maybe a column in your user table.
If you want users to edit the form later, render the checkboxes with a loop and add a "checked" attribute to each checkbox element whose name exists in 'exploded' list (array) retrieved from your database.
This is basically serialization/deserialization. There are other ways to do it including serialize(), unserialize() or json_encode(), json_decode(). But since your data seems to be easily modeled as a basic list, you can keep it even simpler.
let's say I have a list of checkboxes that the user selects.
<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
The user selected Water and it is added to the database. Now the user wants to update the list:
<input type="checkbox" name="utility[]" id="utility[]" value="Water" checked="checked"/>Water<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />
<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />
etc...
How can I check that the utility has already been checked in PHP?
What I've done in the past, to save having hundreds of lines of bloat is this...
First compile all the html in a variable, without any "checked" instances.
$boxes = '';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Water" />Water<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Cable" />Cable<br />';
$boxes .= '<input type="checkbox" name="utility[]" id="utility[]" value="Electricity" />Electricity<br />';
Now I loop over your array of fields to check. I've provided a sample array here too.
$already_checked = array('Water', 'Electricity');
foreach( $already_checked as $ac ) {
$find = 'value="' . $ac . '"';
$replace = $find . ' checked="checked"';
$boxes = str_replace($find, $replace, $boxes);
}
echo $boxes;
You could do something like this:
<input type="checkbox" name="utility[]" value="Water"
<?= in_array('Water', $utilities) ? 'checked="checked"' : '' ?>"
/>
(The $utilities variable above is a stand-in for something like $_REQUEST['utilities'], depending on how your code is structured.)
Like that?
<input type="checkbox" name="utility[]" id="utility[]" value="Water"
<?php
if(isAlreadyChecked("Water"))
echo "checked=\"checked\""
?>
/>Water<br />
<?php
function isAlreadyChecked(value)
{
//Check if it is already checked and return a boolean
}
?>
I tried every variant of the in_array conditional out there and could NEVER get this to work (checking off the checkboxes whose values had been previously selected and thus inserted into the database). I tried complex queries with table joins and no luck with that either. I finally gave up and generated a display:hidden div that opened the array (which for some odd reason I had to IMPLODE rather than explode) and listed its items as comma-separated text. Then I tossed in a little jQuery indexOf() magic to determine if the value of each checkbox was part of said array or not. Took me 10 minutes flat to do this with jQuery, very simple.
Here's some sample code that is live and working fine:
<div class="categories">
<span class="keywords"><?php $categories = array(); $categories = implode(', ', $keywords); echo $categories ?></span>
<em>Please verify category selections with each update.</em><br/>
<?php
include 'db.php';
$sql = mysqli_query($con,"SELECT * FROM categoriesTable ORDER BY Category_Name ASC");
while ($row = mysqli_fetch_assoc($sql))
{
$key = urldecode($row['Category_Name']);
$id = urlencode($row['catID']);
echo "<input type='checkbox' name='Category_Key[]' value='$id' id='cat_$id' $chk> $key<br/>";
}
?>
</div>
CSS sets that div to invisible:
.keywords { display:none; visibility:hidden; }
and the jQuery portion:
$(document).ready(function() {
$('.categories input').each(function(index,data) {
var str=$('.keywords').text();
var catid = $(this).val();
var chk = str.indexOf(catid);
if (chk >= 0) {
$(this).prop('checked', true);
}
});
});
I hope this helps someone else who is stuck wondering why the in_array conditional is failing them. Since this falls in a twilight zone between data and UI regarding data persistence, I think it's a legit route to take. You have one "echo" statement to generate multiple checkboxes (there are around 40 categories in my situation here) and then a simple jQuery .each() to locate what was selected before and render its corresponding boxes as checked.