I'm trying to select all values from my MySQL database. Options a, b, and c work fine but I'm not sure of the syntax to select all three.
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="1,2,3">All</option>
I think you want to use the select to fetch a item or all items if I understand your question correctly and by seeing your 'all' option's value.
If so then change your select option's value for all to <option value="all">all items</option>.
Then change your PHP file (where you posting to with the form) to this:
// is the all option send?
if($_POST['your_select'] === 'all') {
//query to get all the items (SELECT * FROM table)
} else {
// query with the post value as the id (SELECT * FROM table WHERE id = $_POST['your_select'])
}
i think you want multiple="multiple" it will allow you to select multiple
<select name="modules[]" multiple="multiple">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="1,2,3">All</option>
</select>
now you will get array of selected option which you can get by either GET or POST
to select all on selecting last you can use jquery like
$('option').click(function(){
if($(this).val() =='1,2,3'){
$("option").attr("selected", "selected");
}
})
Try this
<form action="my_page.php" method="post">
<select name="my_select">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="1,2,3">All</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
<?php
# in my_page.php page
# put submitted value of the select tag in an array
# (submitted value in this case equals "1", "2", "3" or "1,2,3")
$values = explode(",", $_POST["my_select"]);
# get number of values in the array
$num_of_values = count($values);
# escape all values before using them in your sql statement
foreach ($values as $key => $val) {
$values["$key"] = mysql_real_escape_string($val);
}
# if we have more than 1 value in the array
if (count($values) > 1) {
$sql = "SELECT * FROM table_name WHERE "; # note the space after "WHERE" keyword
for ($i = 0; $i < $num_of_values; $i++) {
# this "if" statement is for removing the "OR" keyword from the sql statement
# when we reach the last value of the array
if ($i != $num_of_values - 1) {
$sql .= "column_name = '{$values[$i]}' OR "; # note the space after "OR"
} else { #if we reached the last value of the array then remove the "OR" keyword
$sql .= "column_name = '{$values[$i]}'";
}
}
# execute your query
$result = mysql_query($sql);
} else { # if we have only one value in the array
$result = mysql_query("SELECT * FROM table_name WHERE column_name = '{$values[0]}'");
}
?>
Related
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;
Please help me, I'm inserting the array (11,7,10) into a table.
Now i want to echo this data:
click here to show table
like this structure iwant to make it
<select>
<option value="11">11- HbA1C</option>
<option value="7">10- O"Solivan Test</option>
<option value="10">7- Randam Blood Glucose</option>
</select>
/////////////////////////////////////
table==>
id name date re_doctor sex age no_ana name_pr
11 aaaa 17/04/2017 Female 11,10,7 11- HbA1C,10- O"Solivan Test,7- Randam Blood Gluco.
////////////////////////////////////////////////
my code :-
<?
$qqq=$_GET['n'];
$sql = "SELECT * FROM `profile` where id ='$qqq'"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$array1[] = $row[6]; // get the username field and add to the array above with surrounding quotes
// get the username field and add to the array above with surrounding quotes
$array3[] = $row[7]; // get the username field and add to the array above with surrounding quotes
}
?>
<select> <option>
<?
foreach($array1 as $it=>$ss){
foreach($array3 as $rr=>$vv){
if ($it==$rr) {
echo str_replace(',', '<option value="'.$ss.'">', $vv .'</option>');
}
}
}
?>
</select>
Lets say your data comes in as 11,7,10 from a multiple option or a checkbox as an array
Do a loop from the incoming form data from the array $no_ana at the user form
foreach($no_ana as $key => $value){
mysql_query("INSERT INTO table_name (id, name, date,
re_doctor, sex, age, no_ana, etc)
VALUES ($val1, $val2, $val3, $val4,
$val5, $val6, $value, $etc");
}
insert this code snippet to your script and test it out.
Here is how you do a multiple attribute
<select multiple name="name_pr[]">
<option value="11">11- HbA1C</option>
<option value="7">10- O"Solivan Test</option>
<option value="10">7 - Ramdam Blood Glocose</option>
</select>
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>
So I'm trying to execute a search using PDO. I have this search set up:
echo "<form action = 'user.php?search=yes' method = 'post' id='searchform'>
<a href='user.php?newuser=yes'>Add New User</a> || Search By
<select name = 'paramet' form = 'searchform'>
<option value = 'userID'>User ID</option>
<option value = 'firstname'>First Name</option>
<option value = 'lastname'>Last Name</option>
<option value = 'email'>E-Mail</option>
<option value = 'mobileno'>Mobile Number</option>
<option value = 'homeno'>Home Number</option>
</select>
<select name = 'howso' form = 'searchform'>
<option value = 'contains'>which contains</option>
<option value = 'equalto'>which is equal to</option>
</select>
<input type = 'text' name='criteria' required>
<input type = 'submit' value='Search'>
</form>
And then this handling the query:
{
$param = $_POST['paramet'];
$how = $_POST['howso'];
$crite = $_POST['criteria'];
if($how == 'contains')
{
$query = $hsdbc->prepare("SELECT * FROM user WHERE :param LIKE :crite");
$query->bindParam(':param', $param);
$query->bindValue(':crite', '%' . $crite . '%');
$query->execute();
}
else{
$query = $hsdbc->prepare("SELECT * FROM user WHERE :param = :crite");
$query->bindParam(':param', $param);
$query->bindParam(':crite', $crite);
$query->execute();
}
I'm getting no-where near the correct results. Any help?
You can't bind column names. The best you can do is add the name to a white list array or something and insert it manually.
if(in_array($param, $good_params_array)) {
$query = $hsdbc->prepare("SELECT * FROM user WHERE $param LIKE :crite");
$query->bindValue(':crite', '%' . $crite . '%');
$query->execute();
}
I've seen people query the DB for the table description to get the columns to see if the column name is listed, but that requires an addition DB request. Also, you might want to limit the fields they can search against
I am currently creating a multiple dropdown query where the user can query by (3) factors for returning results, my issue is how can I do this in an efficient manner so I am not obscurely writing multiple possible MySQL Queries.
<select name="class">
<OPTION VALUE='any'>Choose Class
<option value="a">Block A</option>
<option value="b">Block B</option>
<option value="c">Block C</option>
</select>
<select name="category">
<OPTION VALUE='any'>Choose Type
<option value="math">Math</option>
<option value="science">Science</option>
<option value="history">History</option>
</select>
How can I successfully create a MySQL query that will correctly select the right parameters in the case that a variable is missing. In example, if they choose to do the first dropdown and only search for the "class" and not choose the second dropdown. I want to be able to do the first query, the second query or both of them. I have the PHP, Ajax written, I'm just stumped as to the correct structure of the MySQL query.
Put your "WHERE" clause conditions in one array. I would do like this:
// filter out invalid values is important
$valid_class = array('a', 'b', 'c');
$valid_category = array('math', 'science', 'history');
// initialize array for WHERE clause conditions
$where = array('TRUE');
if (in_array($_POST['class'], $valid_class))
{
$where[] = 'class = "' . $_POST['class'] . '"';
}
if (in_array($_POST['category'], $valid_category))
{
$where[] = 'category = "' . $_POST['category'] . '"';
}
// use the array with the "implode" function to join its parts
$sql = 'SELECT * FROM table WHERE ' . implode(' AND ', $where);
You may want to initialize the $where array with something more interesting than "TRUE" (which is there in case the user does not filter by class neither category, because we don't want an empty $where array reaching the last line). For example:
$where = array();
$where[] = 'name = "' . mysql_real_escape_string($_POST['name']) . '"';
<select name="class">
<OPTION VALUE="">Choose Class
<option value="a">Block A</option>
<option value="b">Block B</option>
<option value="c">Block C</option>
</select>
<select name="category">
<OPTION VALUE="">Choose Type
<option value="math">Math</option>
<option value="science">Science</option>
<option value="history">History</option>
</select>
set the column of the table on ur MySQL to allow null
so when user select " <OPTION VALUE="">Choose Type" or "<OPTION VALUE="">Choose Class", pass Null into the column
Break the query in pieces and use it conditionally
suppose: $class is for class select box and $category is for category select box
$selectquery = "select * from tablename ";
if($class != "" && $category == ""){
$selectquery .= "WHERE class='".$class."'";
}elseif($class == "" && $category != ""){
$selectquery .= "WHERE category ='".$category."'";
}elseif($class != "" && $category != ""){
$selectquery .= "WHERE category ='".$category."' AND class='".$class."'";
}