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
Related
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>
I have form which use below codes:
<select name="ptype">
<option selected="selected" value="">Any</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
now, how can the php page process the "Any" field in mysql. I tried below code, but didnot worked on process page:
$q = mysql_query("SELECT * FROM `listing` WHERE ptype='{$_POST['ptype']}'");
echo mysql_error();
while($r=mysql_fetch_array($q)){
}
There are multiple select option which use "any", all fields run on same query. here any means all value
what may be the error ? or how to use "any" value ?
$ptype = $_POST['ptype'];
if ($ptype == "Any") {
$w = " WHERE 1";
} else {
$w = " WHERE ptype = '" . $ptype . "'";
}
$q = mysql_query("SELECT * FROM `listing`" . $w);
echo mysql_error();
while ($r = mysql_fetch_array($q)) {
....
}
Check for it separately:
SELECT *
FROM `listing`
WHERE '{$_POST['ptype']}' = 'ANY' or ptype='{$_POST['ptype']}'
If any means that both can work, just drop the WHERE clause from your query if $_POST['ptype'] doesn't have a value (or give it a value and check for that).
If the option is any, programitically change your query as :
$q=mysql_query("SELECT * FROM `listing`");
I have a form with a select multiple like this:
<select name="states[]" size="5" multiple>
<option value="2">state 1</option>
<option value="3">state 2</option>
<option value="4">state 3</option>
<option value="5">state 4</option>
<option value="6">state 5</option>
</select>
I want to have the possibility to choose more than one state, and then make the query to my database and show the description of each state chosen.
So this is what I have to make the query using PHP and MySQL:
$state = $_POST['states'];
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
while($row = mysql_fetch_array($data)){
$result=$row['description'];
}
echo $result;
I have that code and it doesn't show anything.
How can I fix this problem?
Try this
$state = $_POST['states']; // return Array
$count_states = count( $state );
if( $count_states > 0) {
$states = implode( ',', $state);
$data = mysql_query("SELECT * from states WHERE id_state IN ($states)",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
This would require a simple foreach to go through the array and get results based on each value as such,
foreach($_POST['states'] as $state) {
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
$row = mysql_fetch_array($data);
echo $row['description'];
}
Also since you're not protecting your query in some sort and are using mySQL which has been deprecated as of PHP 5.5.0, I suggest you looking into PDO or mySQLi Prepared statements
$_POST['states'] holds an Array with all the ID's of the selected states.
Off course you can query your database for every posted state_id, but way nicer (and faster) would it be to make a query which looks like this and uses only one query:
SELECT description FROM states WHERE id_state=1 OR id_state=2 etc etc
This also might be a good point to start using a database abstraction layer like PDO.
As the number of posted states is variable, we need to make the statement also variable:
// The [connection setup][2] by PDO is done in $conn, with some proper exception handlers
// e.g. $conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Fill an array with count() number of elements with value 'id_state=?'
$place_holders = array_fill(0, count($_POST['state']), 'id_state= ?');
//implode the array
$place_holders = implode(' OR ', $place_holders);
// prepare the query
$st = $conn->prepare("SELECT description FROM state WHERE $place_holders");
// execute to above prepared query with the $_POSTED states
$st->execute($_POST['state']);
// traverse the result
foreach($st->fetchAll() AS $r){
// do some magic
}
You could build the string by iterating through the array:
$state = "";
foreach($_POST['states'] AS $s)
{
// Sanitize $s here
$state .= "`id_state` = " . $s . " OR";
}
if($state)
{
$state = substr($state, 0, -3);
$data = mysql_query("SELECT * from states WHERE $state",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
Of course, you should use something like MySQLi or PDO to handle database interaction. They will have ways to sanitize input easily so you can avoid obvious SQL injection.
Tamil has a pretty good IN select method as well. This is just one option.
Example (pages for edit):
//On select_multiple.php (Form):
<?php
//Conn
include('incl_config.php');
//Multiple data to bring
$sql = " select COD_DXS,VALOR_DXS from hc_dxsindromico where ESTADO_DXS='1' ";
$result=#mysql_query($sql);
?>
//In the form select:
<select multiple="multiple" size="7" name="dxsindromico[]"> //look yes or yes brackets []
<option value="" selected="selected">Choose one or more options</option>
<?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['COD_DXS']; ?>" style="color:#F00;"><?php echo $row['VALOR_DXS'];?></option>
<?php } ?>
</select>
//////////// On grabar_mtr.php ///////////////
<?php
include('incl_config.php');
/*Multiple selection form in HTML5, PHP and Bootstraps
Created by: www.nycsoluciones.com
Version: 1.1*/
//we use a foreach to traverse the array (values of our select and save them in the table dxsindromico_data)
if(isset($_POST['dxsindromico'])){
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
//echo $sqli;
//exit;
$resulti=mysql_query($sqli);
}
} else{
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
$resulti=mysql_query($sqli);
}
}
?>
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]}'");
}
?>
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."'";
}