I faced a problem in developing advanced search code using php as an input and output, sql to select and filter data ..
php code:
<form action="index.php?Type=Advance" method="post">
<input type="text" name="name">
<input type="text" name="sponsor">
<select size="1" name="gender" id="">
<option value="male">male</option>
<option value="female">female</femal>
</select>
<select size="1" name="address" id="">
<option value="x">x</option>
<option value="y">y</option>
<option value="z">z</option>
</select>
<input type="submit">
</form>
Then i declare the variables
public function AdvanceSearch($name,$sponsor,$gender,$address)
{
$cheack = "";
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
}
if(isset($sponsor)&&$sponsor != ""){
$cheack.=" AND sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
$cheack.=" AND gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
$cheack.=" AND workplace = '$address' ";
}
$DB = mysql_query("SELECT * FROM table WHERE 1 = 1 ".$cheack);
echo "SELECT * FROM user WHERE ".$WHQ;
exit();
actually it works, however if i didn't insert the name ... the sql statement will be like this
SELECT *
FROM table
WHERE AND sponsor = 'www'
AND gender = 'male'
what if i want to search on the table but without inserting the name .. how can i let the sql statement works if i didn't inset the name.
A typical solution to this is always adding a true condition first, such as 1=1. The query without any extra conditions then becomes
SELECT * FROM table WHERE 1=1
and when you add any AND conditions you can just add them to the end, with no special case for the first or last condition:
SELECT * FROM table WHERE 1=1 AND sponsor = 'www' AND gender = 'male'
Note that if you used OR instead of AND the first condition should be false, like 0=1.
You can use a flag variable like :
$cheack = "";
$flag = False;
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
$flag =True;
}
if(isset($sponsor)&&$sponsor != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
if($flag){
$cheack.="AND ";
}
$cheack.="workplace = '$address' ";
}
Related
I have bootstrap chosen-select multiple select option. It is wokring fine but when i go to insert multiple selections into database it doesnt insert all selected options it inserts only the biggest value from the selected options.
Select Box
<select name="type" data-placeholder="Choose a Card Type..." class="chosen-select" style="text-align: left;" tabindex="2" multiple>
<?php
$q_all_categories = mysql_query("SELECT * from sort_kcc");
while ($all_categories = mysql_fetch_array($q_all_categories)) {
$category_id = $all_categories['id'];
$categories_name = $all_categories['ename'];
$categories_aname = $all_categories['aname'];
$q_selected_cat = mysql_query("
SELECT * FROM rel_sort_kcc WHERE sort_id=".$category_id."
AND sr_id=".$_GET['id']."
");
$selected = "";
while ($category = mysql_fetch_array($q_selected_cat)) {
$selected_category = $category['sort_id'];
if($category_id == $selected_category){$selected = "selected";}
}
print "<option class='ur' ".$selected." value='".$category_id."'>".$categories_name."</option>";
$selected = "";
}
?>
</select>
Insert Query
$categoriesCT = $_POST['type'];
for($i=0; $i < count($categoriesCT); $i++) {
mysql_query("
INSERT INTO
rel_sort_kcc
(sr_id, sort_id)
VALUES
('".$_POST['idName']."', '".$categoriesCT[$i]."')
");
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
EDIT: I have now attempted to do my PHP code again, it kind of works now but except its prints all the lessons each time you press submit not the lessons around the filter. Also I can't seem to connect two tables together when filtering. The Instructor's name is from a different table instructor and I would like to pick this up. Here is my PHP code.
<?php
include('connect-db.php');
if($_POST){
if($_POST['Days'] == 'Monday') {
$query = "SELECT * FROM lesson WHERE Day='Monday'";
}elseif($_POST['Days'] == 'Tuesday') {
$query = "SELECT * FROM lesson WHERE Day='Tuesday'";
}elseif($_POST['Days'] == 'Wednesday') {
$query = "SELECT * FROM lesson WHERE Day='Wednesday'";
}elseif($_POST['Days'] == 'Thursday') {
$query = "SELECT * FROM lesson WHERE Day='Thursday'";
}elseif($_POST['Days'] == 'Friday') {
$query = "SELECT * FROM lesson WHERE Day='Friday'";
}elseif($_POST['Days'] == 'Saturday') {
$query = "SELECT * FROM lesson WHERE Day='Saturday'";
}elseif($_POST['Days'] == 'Sunday') {
$query = "SELECT * FROM lesson WHERE Day='Sunday'";
}elseif($_POST['Days'] == 'All') {
$query = "SELECT * FROM lesson";
}
if($_POST['Instructors'] == 'Trevor') {
$query = "SELECT * FROM lesson INNER JOIN instructor
ON lesson.Instructor_ID = instructor.Instructor_ID WHERE Forename='Trevor'";
}elseif($_POST['Instructors'] == 'Laura') {
$query = "SELECT * FROM lesson INNER JOIN instructor
ON lesson.Instructor_ID = instructor.Instructor_ID WHERE Forename='Laura'";
}elseif($_POST['Instructors'] == 'Rachel') {
$query = "SELECT * FROM lesson INNER JOIN instructor
ON lesson.Instructor_ID = instructor.Instructor_ID WHERE Forename='Rachel'";
}elseif($_POST['Instructors'] == 'Ryan') {
$query = "SELECT * FROM lesson INNER JOIN instructor
ON lesson.Instructor_ID = instructor.Instructor_ID WHERE Forename='Ryan'";
}elseif($_POST['Instructors'] == 'Steve') {
$query = "SELECT * FROM lesson INNER JOIN instructor
ON lesson.Instructor_ID = instructor.Instructor_ID WHERE Forename='Steve'";
}elseif($_POST['Instructors'] == 'All') {
$query = "SELECT * FROM lesson INNER JOIN instructor
ON lesson.Instructor_ID = instructor.Instructor_ID";
}
if($_POST['TypeLessons'] == 'Keeping Fit') {
$query = "SELECT * FROM lesson WHERE Type_of_Lesson='Keeping Fit'";
}elseif($_POST['TypeLessons'] == 'How to Swim') {
$query = "SELECT * FROM lesson WHERE Day='How to Swim'";
}elseif($_POST['TypeLessons'] == 'Relaxing Sessions') {
$query = "SELECT * FROM lesson WHERE Day='Relaxing Sessions'";
}elseif($_POST['TypeLessons'] == 'Being Sporty') {
$query = "SELECT * FROM lesson WHERE Day='Being Sporty'";
}elseif($_POST['TypeLessons'] == 'All') {
$query = "SELECT * FROM lesson";
}
$result = mysql_query($query);
if(!$result) {
echo 'Could not get data: ' . mysql_error();
}
while($row = mysql_fetch_array($result)) {
echo "Lesson ID: {$row["Lesson_ID"]} <br> " .
"Name: {$row["Name"]} <br> " .
"Day: {$row["Day"]} <br> " .
"Start Date: {$row["Start_Date"]} <br> " .
"Start Time: {$row["Start_Time"]} <br> " .
"End Time: {$row["End_Time"]} <br> " .
"Instructor: {$row["Forename"]} <br> " .
"Type of Lesson: {$row["Type_of_Lesson"]} <br> " .
"Number of Places: {$row["No_of_Places"]} <br> <br> ";
}
}
?>
I have been trying to filter multiple drop down menu options so that when the user clicks 'search lessons' the queries appear. But for some reason I keep getting the same error message: Notice: Undefined index: Days.
Even though the php code should be picking it up, it doesn't seem to be and I can't figure it out. This is my code below, note I haven't finished selecting all my PHP.
Also how do I print out these queries too once I select these options upon selecting PHP. Thank you so much.
<form action="tester_filter.php" method="post">
<select name="Days">
<option value="All" selected="selected">All days</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
<select name="Instructors">
<option value="All" selected="selected">All instructors</option>
<option value="Trevor">Trevor</option>
<option value="Laura">Laura</option>
<option value="Rachel">Rachel</option>
<option value="Ryan">Ryan</option>
<option value="Steve">Steve</option>
</select>
<select name="TypeLessons">
<option value="All" selected="selected">All types</option>
<option value="Keeping Fit">Keeping Fit</option>
<option value="How to Swim">How to Swim</option>
<option value="Relaxing Sessions">Relaxing Sessions</option>
<option value="Being Sporty">Being Sporty</option>
</select>
<input type="submit" value="search lessons" name="submit" />
</form>
<?php
if($_POST){
if($_POST['Days'] == 'Monday') {
$query = "SELECT * FROM lesson WHERE Day='Monday'";
}elseif($_POST['Days'] == 'Tuesday') {
$query = "SELECT * FROM lesson WHERE Day='Tuesday'";
}
}
?>
try this one
to fix the notice error use the below code.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['Days'] == 'Monday') {
$query = "SELECT * FROM lesson WHERE Day='Monday'";
}
elseif($_POST['Days'] == 'Tuesday') {
$query = "SELECT * FROM lesson WHERE Day='Tuesday'";
}
}
alternatively you can also check by below code
if(!empty($_POST)) {
// process, validate or save to DB $_POST values,
}
Assuming your PHP script is located in tester_filter.php like the form suggests (you didn't actually state its there), I'm not sure what you're expecting to get out, the Days is being picked up, however you're only setting a variable called Query to a string, and not doing anything with it.
In each of the if statements, do a debugging
if($_POST['Days'] == 'Monday') {
//A check we're having the variable pass through
echo "this should say monday";
$query = "SELECT * FROM lesson WHERE Day='Monday'";
}
If you're trying to check if you're selection is good (it looks okay), then select monday and see if the echo is output, then you're looking good.
You can't just assign a Query without a connection to a database, you need a connection string, such as, for example:
//Connection variables
$servername = "localhost";
$username = "root";
$password = "password";
$database = "database";
//Connect to MySQL
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "Connected successfully";
}
Then once you have that very base, you can start Querying the database, using what you've done with $Query.
It's probably too much for me to explain so i'll leave as many helpful links as I think you'll need to help you on your way.
Connect to a MySQL Database from PHP
Pulling data from a MySQL Database, Querying the Database through PHP
List of MySQLi functions and what they do
Another list of MySQLi functions and what they do
Another guide on how to select information from a MySQL Database
Good luck, and comment if you have any problems.
I have a random chat feature which allows users to randomly pair against another based on the parameters set by the user. The parameters are age (min: 17, max: 50) and gender (can chat with male, female, or any which means no preference).
When submit is clicked, it is easy to set queries if the radio values are male or female, because those are the values I am storing in my database, but I am unsure on how I can pair someone with another if the value is any.
Here are the radio buttons:
<input type="radio" name="gender" value="male">Male</input> <br />
<input type="radio" name="gender" value="female">Female</input><br />
<input type="radio" name="gender" value="any">Any</input>
<input type="submit" class="btn btn-info" name="submit" value="Click to start chat! " />
P.s. The radio buttons are in a form but have no action.
<form action="#" method="POST" enctype="multipart/form-data">
And here is my approach so far:
<?php
$age_from = #$_POST['age_from'];
$age_to = #$_POST['age_to'];
$gender = strip_tags(#$_POST['gender']);
if (isset ($_POST ['submit'])){
// Chat with parameters script
$any_chat = mysqli_query($connect, "SELECT * FROM users WHERE age BETWEEN '$age_from' AND '$age_to' AND gender = '$gender'
ORDER BY RAND() LIMIT 1");
$num_of_rows = mysqli_num_rows ($any_chat);
while ($get_any_rand_user = mysqli_fetch_assoc($any_chat)){
$rand_name = $get_any_rand_user['username'];
$acc_type = $get_any_rand_user['account_type'];
if ($acc_type != "admin" ){
if ($rand_name == $username){
$any_chat;
} else{
header ("Location: /messages.php?u=$rand_name");
}
}
if ($num_of_rows == 0){
echo "No results found. Try changing your query.";
}
} // while closed
}
?>
As you can see in the query gender = '$gender' can only retrieve a row if the gender is male or female (because they are the values in the db). But if any is selected, $gender will equal any which is not valid, since their is no user in my system with gender of any.
How can I work my way around this?
I would do something like this. Create a variable to store your query and only add the gender condition if $gender is male or female.
<?php
$age_from = #$_POST['age_from'];
$age_to = #$_POST['age_to'];
$gender = strip_tags(#$_POST['gender']);
if (isset ($_POST ['submit'])){
// Chat with parameters script
$sql = "
SELECT *
FROM users
WHERE age BETWEEN '$age_from' AND '$age_to'
";
if (!empty($gender) && ($gender == 'male' || $gender == 'female')) {
$sql .= " AND gender = '$gender' ";
}
$sql .= " ORDER BY RAND() LIMIT 1 ";
$any_chat = mysqli_query($connect, $sql);
$num_of_rows = mysqli_num_rows ($any_chat);
while ($get_any_rand_user = mysqli_fetch_assoc($any_chat)){
$rand_name = $get_any_rand_user['username'];
$acc_type = $get_any_rand_user['account_type'];
if ($acc_type != "admin" ){
if ($rand_name == $username){
$any_chat;
} else{
header ("Location: /messages.php?u=$rand_name");
}
}
if ($num_of_rows == 0){
echo "No results found. Try changing your query.";
}
} // while closed
}
?>
if (isset ($_POST ['submit'])){
// Chat with parameters script
$sql_builder = "SELECT * FROM users WHERE age BETWEEN '$age_from' AND '$age_to'";
if($gender != 'any'){
$sql_builder .= "AND gender = $gender";
}
$sql_builder .= "ORDER BY RAND() LIMIT 1";
$any_chat = mysqli_query($connect, $sql_builder);
I want to ask about this code. I have two dropdown menu and one button. I want to search in sql database what I choose in those drop down menu. What is the sql syntax for search item in sql database by using two drop down menu.
my database = test
Table = student
name | class | sex | mark |
John | Five | Male | 75
Jashi | Four | Female | 89 |
##HTML##
<form action="search2.php" method="post">
<select name="class">
<option value="" selected="selected">Class</option>
</select>
<select name="sex">
<option value="" selected="selected">Sex</option>
</select>
<input type="submit" value="search" />
</form>
search2.php
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
$whereClauses = '';
$class = count($_POST['class']);
$sex = count($_POST['sex']);
$i = 0;
if (! empty($_POST['class'])) {
foreach ($_POST['class'] as $class) {
$whereClauses .="class='".mysql_real_escape_string($class)."'";
if ($i++ == $class) {
$whereClauses .= " AND";
}
}
}
if (! empty($_POST['sex'])) {
foreach ($_POST['sex'] as $sex) {
$whereClauses .="sex='".mysql_real_escape_string($sex)."'";
}
if ($i++ == $sex) {
$whereClauses .= " AND";
}
}
$sql = "SELECT * FROM student '".$where."' ORDER BY id DESC '".$limit."'";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['class'];
echo $row['sex'];
echo $row['mark'];
}
?>
ANY HELP WOULD BE APPRECIATED
If I got it right and you want to search for students by class and sex (gender?) you can use this SQL query:
SELECT * FROM `student` WHERE `class` = 'the_class' AND `sex` = 'the_sex';
Where:
the_class is the input from your choose Class dropdown
the_sex is the input from your choose Sex dropdown
If I understand it correctly, you want the input of two drop down menu's to define the Mysql query? In that case, you can simply first check whether the user has selected two values, and then you could change your query accordingly by adding the "AND" to the Mysql Query.
For example:
if(isset($_GET["class"]) && isset($_GET["sex"])) {
$result = mysql_query("SELECT * from student Where sex = '". $_GET["sex"]."' AND class = '".$_GET["class"]."'");
}
Of course, in the above mentioned solution I presume that you are aware how to POST and GET data through html forms and PHP.
I am trying to search in MySql db based on user input something like below.
User may/not select from the below fields
<select name="field_one" id="f1">
<option value="AA">AA</option>
<option value="BB">BB</option>
<option value="CC">CC</option>
</select>
<select name="field_two" id="f2">
<option value="11">11</option>
<option value="22">22</option>
<option value="33">33</option>
</select>
if User selects only 'field_one', then mysql_query should filter only based on 'field_one'. In this case there can be four combination
Filed_one is slected and filed_two is not selected
Field_One is not selected and field_two is selected
Filed_one is not selected and Filed_two is not selected
Field_one is selected and Field_Two is selected
What is the best and efficient methode to make this search?
I tried with 'case .... break;' and 'if', but when the first condition is met, code stops and does not check the next conditions
Can any one give me a clue? Thanks in advance for the help....
try this:-
$query = "select * from table_name where 1 ";
if(!empty($_POST['field1']) ) {
$query .= " AND field1 like '".trim($_POST['field1'])."'";
}
if(!empty($_POST['field2'])) {
$query .= " AND field2 like '".trim($_POST['field2'])."'";
}
// and so on
$result = mysql_query($query);
please use escape string also http://php.net/mysql_real_escape_string
<?php
$sql = "SELECT * FROM table_name WHERE 1";
if(isset($_POST)){
if(isset($_POST['field_one'])){
$sql.= 'AND field_one'= $_POST['field_one'];
}
if(isset($_POST['field_two'])){
$sql.= 'AND field_two'= $_POST['field_two'];
}
}
mysql_query($sql);
?>
Example, not tested and needs lots of variable processing against SQL injection
$where = "";
$bits = array();
$bitset=false;
if(isset($_POST['field_one') && strlen($_POST['field_one')) > 0)
{
$bitset = true;
$bits[] = " field1 = $_POST['field_one')"
}
if(isset($_POST['field_two') && strlen($_POST['field_two')) > 0)
{
$bitset = true;
$bits[] = " field2 = $_POST['field_two')"
}
if($bitset)
{
$where = implode(", " $bits);
}
$sql = "select * from table " . $where;
You can also use PDO & param binding to avoid SQL Injection : http://www.php.net/manual/fr/pdostatement.bindparam.php