Build Query From List Box In PHP - php

I have a page where I am wanting to allow a user to select fields from a select that exist in a table, then display the contents of those fields on screen. I have set-up the select like so
<select name="queryfields" size="12" multiple="multiple" tabindex="1">
<option value="firstname">firstname</option>
<option value="lastname">lastname</option>
<option value="address">address</option>
<option value="phone">phone</option>
And I know to discover what options were selected I can use this:
<?php
header("Content-Type: text/plain");
foreach ($_GET['queryfields'] as $selectedOption)
echo $selectedOption."\n";
?>
And that gives me an array of the fields selected. However, how do I then parse the array to generate my full query? For example, let's say that firstname, lastname were selected. I would then want to build my query like this:
Select firstname, lastname from employeedata
Unknown to me, is how to get the data from the array into a select statent like my above code snippet.

Try This:
$sql = '';
$selected_fields = array();
foreach ($_GET['queryfields'] as $selectedOption){
//echo $selectedOption."\n";
$selected_fields[] = $selectedOption;
}
if(!empty($selected_fields)){
$fields = implode(',', $selected_fields);
$sql = 'SELECT '.$fields.' from employeedata';
}
//print query if it is not empty
if(!empty($sql)){
echo $sql;
}

You can use PHP implode() function.
<?php
header("Content-Type: text/plain");
$q = "SELECT ".implode(', ', $_GET['queryfields'])." FROM employeedata";
?>
But there are some possibilities for SQL injection. You should read the about that before proceeding. How can I prevent SQL injection in PHP?
You can create a design like the below
<?php
header("Content-Type: text/plain");
$filter = array_filter($_GET['queryfields'], function($val) {
$allowedFields = array(
'firstname',
'lastname',
'address',
'phone',
);
return in_array($val, $allowedFields);
}
$q = "SELECT ".implode(', ', $filter)." FROM employeedata";
?>

Related

Order list of options based on MySQL query - PHP

I am presenting a list of options to the user based on a database query. The results are being fetched correctly however they are currently unordered and I would like to display them in alphabetical order in the option list. I have tried several solutions so far with "ORDER BY" on the query level however with no success. Is there a simple way to achieve this? (The list contains 1000+ results) The code is as follows:
<?php
$user_id = $_SESSION['user_id'];
$sql = "SELECT * FROM add_bulding WHERE description<>''";
$query = $this->db->query($sql);
$building_title = $query->result_array();
?>
<div>
<select>
<option value="">Select Building</option>
<?php foreach ($building_title as $value) { ?>
<option value = "<?php echo $value['id']; ?>">
<?php echo $value['title']; ?>
</option>
<?php
}
?>
</select>
</div>
Try changing your query to:
$sql = "SELECT * FROM add_bulding WHERE description<>'' ORDER BY title DESC";
Sounds like you want a query like:
SELECT id, title FROM add_bulding WHERE description<> ORDER BY title desc
Alternately, you can sort it in php:
<?php
$tmp = array();
foreach ($building_title as $value){
$tmp[$value['id']] = $value['title'];
}
ksort($tmp);
foreach ($tmp as $k => $v) {
print "<option value=\"" + $k + "\">" + $v + "</option>\n";
}
?>
However, in either case, be sure to sanitize your values so you don't end up with XSS problems.
Try this query :
$sql = "SELECT * FROM add_bulding WHERE description<>'' ORDER BY title";
If you want to get title data with alphabetical order then you can write 'ASC' or do not need to write any after ORDER BY title.
But you want to get title data with descending order then you need to write 'DESC' after ORDER BY title
I hope you will get solution.

Display all data in dropdown from database

i am using Php/Mysql , i have the client table and trying to display data in a drop down list. Unfortunately, only one client is displayed in drop down which i have the total of 3 clients. Why only one ? For example : Michael King, Michael Jordan , Michael John when i select all the data from table and make an output to display in dropdown, Michael John is only in the dropdown.
Here my Mysql code :
//All data is selected from client_tb
<?php
$sql = "SELECT * FROM client_tb";
$result = $conn->query($sql);
while($row=mysqli_fetch_array($result))
{
$id = $row['id'];
$lname = $row['lname'];
$fname = $row['fname'];
}
?>
//my dropdown which will show the clients from client_tb but only one will appear.
<option value ="<?=$lname?><?=$fname?>"><?=$lname?> , <?=$fname?> </option> </select><br><br>
You can also achieve dropdown outside the while loop. Try this:
$sql = "SELECT * FROM client_tb";
$result = $conn->query($sql);
$options =array();
while($row=mysqli_fetch_array($result))
{
$options[] =$row;
}
Your dropdown:
<select name="">
<?php
foreach($options as $option):
echo '<option value ="'.$option['lname'].''.$option['fname'].'">'.
$option['lname'].','.$option['fname'].'</option>';
endforeach;
?>
</select>
You could also add your db query into a function , then call it.
function myFunction() {
$sql = "SELECT * FROM client_tb";
$result = $conn->query($sql);
while($row=mysqli_fetch_array($result))
{
$myvalues[] =$row;
}
return $myvalues;
}
Now the dropdown,
Note the options are inside the loop
<select name="">
<?php foreach($myvalues as $myvalue) {
echo '<option value="'.$myvalue['lname'].''.$myvalue['fname'].'">'.
$myvalue['lname'].','.$myvalue['fname'].'</option>';
}
?>
</select>

Get value form same table

I have dropdown menu with 3 values.
and here is my table (table name is Sms)
What I want to do? Example : If I choose 2,49 and press submit, then I get sonum value.
This is my form
<div class="col_12" style="margin-top:100px;">
<div class="col_6">
<label for="asukoht">Vali Hind</label>
<form class="vertical" method="GET">
<select name="hind">
<option value="1">-- Vali --</option>
<?php
// Tegin dropdown menüü, kust saab valida komponendi, mille alla see pilt läheb
$andmed = mysql_query("SELECT * FROM Sms");
// Dropdown menüü
while($rida = mysql_fetch_array($andmed)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
?>
<input type="submit" name="add" id="add">
</form>
I tried something like this
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
I think it should be pretty easy, but I'm looking for a solution and I didnt found it.
Thank you for helping !
You need to work on SQL and Loop.
Based on your code:
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
First we do change the query including $_GET parameter.
So this:
$sql = "SELECT sonum FROM `Sms`";
Will become:
$sql = "SELECT sonum FROM `Sms` WHERE id = ".$_GET['hind'];
It will be better if you check that the var exist and is setted with something like:
if(isset($_GET['hind']) && is_numeric(trim($_GET['hind']){//Code here}
But it is off-topic.
Now let's change echo $sql; with a loop, we need to loop and fetch the data.
while($result = mysql_fetch_array($sql)){
echo '<option value="'.$result ['id'] . '">'.utf8_encode($result ['hind'] ). '</option>';
}
I've only changed what i know, you know your system ^_^
You should do:
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
Then do :
echo mysql_query($sql);
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
while($rida = mysql_fetch_array($sql)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
Do not use MYSQL queries...try MySQLi or PDO with prepared statement.

Select multiple (PHP and MySQL)

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);
}
}
?>

Posted multiselect box selection to database only adding the first selected item

i am using the following multiselect box to take input from users, this then gets posted to my php form which adds it to the database, the problem is, all I am getting added is the first selection, if the user selects more than one field I still only get the first field.
If the user selects lets say internet, drawing,maths I want that to be put into the database, at the moment all that is inserted is internet, or whatever is the first thing selected in the list.
My form looks like this >>
<form action="../files/addtodb.php" method="post" style="width:800px;">
<select name="whatisdeviceusedfor[]" size="1" multiple="multiple" id="whatisdeviceusedfor[]">
<option value="games">Games</option>
<option value="takingphotos">Taking Photos</option>
<option value="maths">Maths</option>
<option value="reading">Reading</option>
<option value="drawing">Drawing</option>
<option value="internet">Internet</option>
<option value="other">Other (enter more info below)</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
The php side looks like this >>
<?php
// Implode what is device used for
$usedfor = $_POST['whatisdeviceusedfor'];
$arr = array($usedfor);
$whatisdeviceusedfor = implode(" ",$arr);
// Insert posted data into database
mysql_query("INSERT INTO itsnb_year5questionaire (whatisdeviceusedfor) VALUES '$whatisdeviceusedfor'") or die(mysql_error());
?>
you are already getting array by select so you dont need to use $arr = array($usedfor);this again
just try
$usedfor = $_POST['whatisdeviceusedfor'];
$whatisdeviceusedfor = implode(" ",$usedfor);
or
$usedfor = $_POST['whatisdeviceusedfor'];
$strings ='';
foreach ($usedfor as $item){
$strings .=' '. $item;
}
echo $strings;
and
<select name="whatisdeviceusedfor[]" size="5" multiple="multiple" id="whatisdeviceusedfor[]">
^^
||change to option you want to select
i have changed size="5" so it will select now 5 at a time ...you have only 1 so it will let only 1 select at a time
result
warning
your code is vulnerable to SQL injection also use of mysql_* function are deprecated use either PDO or MySQLi
If you have selected mutliple items via a SELECT or via CHECKBOXES, the form will return an array-like data structure. You will always need to loop over that data and store each item individually into the database or concatenate the values to a string before inserting.
first change size = "5" to see good the list
then try to make like that (its second option if you like it)
if ($_POST) {
// post data
$games = $_POST["games"];
$takingphotos = $_POST["takingphotos"];
.
...
// secure data
$games = uc($games);
$boats = uc($takingphotos);
.
...
}
// insert data into database
$query = "INSERT INTO itsnb_year5questionaire (games, takingphotos,....)
VALUES('$games','$takingphotos',......)";
mysql_query($query) or die(mysql_error());
echo 'Thanks for your select!';
Because $usedfor is contain the array you can directly use it in foreach to save the each value in the value.Try this it may help you:
<?php
$usedfor = $_POST['whatisdeviceusedfor'];
foreach($usedfor as $arr){
mysql_query('INSERT INTO itsnb_year5questionaire(whatisdeviceusedfor) VALUES("'.$arr.'"') or die(mysql_error());
}

Categories