I currently have a html / PHP webpage which uses a series of user inputs to query a SQL database and return data for plotting. The user input is driven by html checkboxes, driven by data in the SQL database and created using PHP code. The entire html code is too large to put on here but below is an excerpt of the part I want to ask about...
...
<div id="AccProject" class="w3-hide">
<?php
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS ORDER BY Project ASC";
$resultProject = $dbhandle->query($queryProject) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
while($row=mysqli_fetch_array($resultProject)){
echo "<input id='".$row['ProjID']."' value='".$row['ProjID']."' name='projID[]' type='checkbox' class='chkbox'>";
echo "<label title='".$row['Description']."
Project: ".$row['Project']."
Sample: ".$row['Sample']."
Type: ".$row['Type']."' for='".$row['ProjID']."' class='chkbox-label'> ".$row['Project']." | ".$row['Sample']." | ".$row['Type']."</label>";
}
?>
</div>
...
You can see that I query the SQL database, return a number of fields and then use PHP to generate a number of checkboxes. Later the in the html, I use javascript to extract the checked / unchecked state of these checkboxes and query the database again to return more data.
What I'd like to do is add a number of pre-filters which will reduce the number of checkboxes visible to the user on the page. For example, if the 'Type' field defines whether the data entry is a 'Cake', 'Biscuit' or 'Pudding', I would like to add some switches which would then amend the SQL query. I've given an example with some pseudo code below.
...
<div id="AccProject" class="w3-hide">
<label class="form-switch"><input type="checkbox" id="filterCake"><i></i> Select Cakes only </label>
<label class="form-switch"><input type="checkbox" id="filterBiscuit"><i></i> Select Biscuits only </label>
<label class="form-switch"><input type="checkbox" id="filterPudding"><i></i> Select Puddings only </label>
<?php
if filterCake == True
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type == 'Cake' ORDER BY Project ASC";
if filterBiscuit == True
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type == 'Biscuit' ORDER BY Project ASC";
if filterPudding == True
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type == 'Pudding' ORDER BY Project ASC";
$resultProject = $dbhandle->query($queryProject) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
while($row=mysqli_fetch_array($resultProject)){
echo "<input id='".$row['ProjID']."' value='".$row['ProjID']."' name='projID[]' type='checkbox' class='chkbox'>";
echo "<label title='".$row['Description']."
Project: ".$row['Project']."
Sample: ".$row['Sample']."
Type: ".$row['Type']."' for='".$row['ProjID']."' class='chkbox-label'> ".$row['Project']." | ".$row['Sample']." | ".$row['Type']."</label>";
}
?>
</div>
...
How can I achieve this with my code?
All I need to do is change the SQL query within the PHP code (adding a WHERE clause) based on the state of the cake, biscuit or pudding checkboxes but I've been struggling to see how to do this.
Any help greatly appreciated!
You will have to do it with AJAX and each time the user clicks on a checkbox send the value to a different page and then you can either loop thru the results with PHP in the other page and return it in HTML or return the results and loop thru it with JS on the checkbox page
See a somewhat example:
$("#formName").on("change", "input:checkbox", function(){
//send $(this).val() with ajax
//Assuming you are selecting cakes and
//getting back an array with cakes
//you are the looping thru the array and gettig populating the html
var response = [];
var cakes = {};
cakes.description = 'Cake Description 1';
cakes.project = 'Cake Project 1';
response.push(cakes);
cakes = {};
cakes.description = 'Cake Description 2';
cakes.project = 'Cake Project 2';
response.push(cakes);
var formattedResponse = '';
response.forEach(function(res){
formattedResponse += `This is ${res.description} <br>`});
$('#responseContainer').html(formattedResponse);
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<form action="" id="formName">
<label class="form-switch"><input type="checkbox" value="cake" id="filterCake"><i></i> Select Cakes only </label>
<label class="form-switch"><input type="checkbox" value="biscuits" id="filterBiscuit"><i></i> Select Biscuits only </label>
<label class="form-switch"><input type="checkbox" value="puddings" id="filterPudding"><i></i> Select Puddings only </label>
</from>
<div id="responseContainer"></div>
yes you can fetch data from database by making a dynamic query. Please try this.
$type = $post['type']; //'Cake','Biscuit','Pudding'
$queryProject = "SELECT DISTINCT ProjID, Project, Sample, Type, Description FROM PROJECTS WHERE Type = '" . $type ."' ORDER BY Project ASC";
Related
I want to get selected values (of which multiple selections are possible) from my database generated dropdown menu and store those into a PhP variable. I then wish to display the content of that variable into a simple div element below.
This is my code so far which results in nothing inside my simple div:
<form id="menu1" method="POST">
<h2>Area Code</h2>
<select id="multi-select1" name="multi_select1" multiple="multiple">
<?php
//The query asking from our database
$areaCodeSQL = "SELECT ac.Number AS `AreaCode`, ac.Name AS `AreaName`
FROM `AreaCodes` ac"; //SQL query: From the table 'AreaCodes' select 'Number' and put into 'AreaCode', select Name and put into 'AreaName'
$areaCodeResults = $conn->query($areaCodeSQL); // put results of SQL query into this variable
if ($areaCodeResults->num_rows > 0) { // if num_rows(from $results) is greater than 0, then do this:
// output data of each row
foreach($areaCodeResults as $areaCodeResult) //for each item in $areCodeResults do this:
{
$areaNameAndCode = $areaCodeResult['AreaCode'] ." ". $areaCodeResult['AreaName']; //get AreaCode and AreaName from query result and concat them
$areaName = $areaCodeResult['AreaName']; // get AreaName
$areaCode = $areaCodeResult['AreaCode']; //get AreaCode
?><option class="menuoption1" name="menuAreaCode" value="<?php echo $areaCode ?>" ><?php echo $areaNameAndCode; ?></option><?php //Create this option element populated with query result variables
}
}
$result = $_POST['multi_select1'];
?>
</select>
</form>
<div id="showResults1"><?php echo $result ?></div>
Looking around online suggests I might need to use AJAX and jQuery but my tutor buddy insists this can be done within this one script. But I have no idea why my attempt does not work, can some one point me in the right direction???? :-)
Its a bit hard to express what I want to do but let me give it a shot.
First of all I have a database with a table. One of the columns from that table I will be showing in a select dropdown menu in HTML, to be more precise: this outputs the column 'name' in the dropbown menu:
<?php
$query = mysql_query("SELECT name from table");
echo "<select name='select1'>";
while ($row = mysql_fetch_array($query))
{
echo "<option value'" . $row['name'] ."'>" . $row['name] . "</option>;
}
echo "</select>";
?>
Then when a value is selected in that dropdown, that value needs to be saved in a variable.
if (isset($_POST['button']))
{
$select = $_POST['select1'];
}
As last bit, the value in variable $select needs to be used to make a SELECT query. I want to use that variable in the SELECT statement to look for the corresponding row (in the same table) that is related to the value in the dropdown menu and pick a column and output that value to a textbox or checkbox, depending on as what the value needs to be outputted.
Example:
TABLE
id - name - street - number - ...
row 1: 0 - test1 - teststreet1 - 1 - ...
row 2: 1 - test2 - teststreet2 - 2 - ...
row 3: 2 - test3 - tesstreett3 - 3 - ...
1) I select test2 from the dropdown menu (dropdown menu is filled with the column name from database)
2) test2 is saved as a variable in $name
3) select query searches for value of street column where $name = test2
SELECT street from table where ?
row 2: 1 - test2 - tesstreett2 - 2 - ...
So I want teststreet2 from street to be outputted in a textbox
<input type='text' value='?'>
I need help with the select query or how to call this.
Thanks in advance and taking time to read this!
Kind Regards
Found it!:
if(isset($_POST['select1']))
{
$select = $_POST['select1'];
$street_select = mysql_query("SELECT street FROM table WHERE name = '" .&select. "'");
$street = mysql_fetch_array($street_select);
$resul_street = $street['street'];
}
Now I can do this for every value in each column that is asked via the dropdown menu!
You can not change a state of any loaded dropdown or text as it is.
You must use jQuery/Ajax here.
When you select on Dropdown value it will than trigger Ajax/jQuery and call another page where your select query will run and return value, which you can display in textbox using jQuery.
<select name = 'select1' onchange='return get_street()'>
<option name='test1'>test1</option>
<input type="text" name ="street" id="street" value="" />
<script>
function get_street()
{
var selected_val = $('option:selected', this).val();
$.ajax({ //ajax call
type: "POST", //method == POST
url: "street.php", //url to be called
data: "name="+selected_val, //data to be send
success: function(data){
$('#street').val(data); // here we will set a value of text box
}
});
}
</script>
And your street.php will look like
<?php
$name = $_POST['name'];
$res = mysql_query("select street from table where name = '".$name."'");
$row = mysql_fetch_assoc($res);
return $row['street']; // this will return a name of street
?>
Few things you need to make sure is
give appropriate path of your file in ajax
give id to your text input and same should be in ajax success
you must connect database in your street.php
Hi so I have two tables in my database and they are structured as follows:
1) services Table:
service_id, service_name
2) business_services_offered table:
record_id, business_id, service_id_fk
When business owners sign up for my website they select the services their business offers using a simple form with checkboxes like this (I've only included two services to make things simple):
<form action ="insert_services.php">
<input type="checkbox" name="lang[ ]" >Behavior supports<br><br />
<input type="checkbox" name="lang[ ]" >Case Management<br><br />
</form>
This system is very straight forward and works fine but I'd like to use a similar form to allow businesses to edit the services they offer should they need to.
What I don't know how to do is how to dynamically generate the "edit form" based on the information contained in the database. To be clearer, let's say a business owner only checked off behavior supports when they originally signed up for the site.
So the corresponding record in the business_services_offered table would look like this:
record_id | business_id | service_id_fk
1 0000023 1
Oh and the services table looks like this:
service_id | service_name
1 Behavior supports
2 Case Management
Now the same owner decides they want to edit the services they offer...how would I dynamically show them a checkbox form with their services (in this case Behavior supports) already checked off.
Obviously, I'd sequel the database and join the two tables using services.service_id and business_services_offered.service_id_fk but during the while loop that produces the form, how would I cause behavior supports to already be checked off? Im guessing some sort of if statement but I'm not sure.
Any help would be greatly appreciated!
Here is the query I'm guessing would work
$query = "SELECT service_name, service_id, business_name" .
"FROM services, business_services_offered " .
"WHERE services.service_id = business_services_offered.service_id_fk";
$result = mysql_query($query)
or die(mysql_error());
And the while loop would look like this I guess:
while($row = mysql_fetch_array($result)){
$service_name = $row['service_name'];
echo "<form action ='edit_services.php'>" .
"<input type='checkbox' name='lang[ ]' >$service_name<br><br />" .
"<input type='checkbox' name='lang[ ]' >$service_name<br><br />" .
"</form>";
}
So again, how would I make sure that the checkbox for behavior supports was checked off.
Thanks!
Here is the form code and the jQuery
I will edit this answer in a minute with the separate PHP file to handle the DB query
<!-- Must include jQuery Library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
// Lets build the Services form
${'The Form'} = '<form name="editServicesForm" id="editServicesForm" action="edit_services.php" method="POST">
<h2>Services</h2>';
// query the service table
$query = mysql_query('SELECT * FROM `services`');
while($row = mysql_fetch_assoc($query)){
${'The Form'} .= '<label><input type="checkbox" name="CheckboxGroup[]" value="'.$row['service_id'].'" id="CheckboxGroup_0" />'.$row['service_name'].'</label><br />';
}
${'The Form'} = '</form>';
// add the form on the page where you need with this
?>
<?= ${'The Form'}; ?>
<!-- The jQuery to do the magic -->
<script type="text/javascript">
// waits for the document to finish loading so all the elements are there to manipulate
$(document).ready(function() {
// your users id to reference the services in the database query
var businessID = "1" // replace this with the users id
// Do a basic post to and external php file
$.post('post.api.php', {'api': 'getServices', 'business_id': businessID}, function(resp){
// parse the response and check the boxes
var obj = $.parseJSON(resp);
// loop through the services returned as active (checked)
$.each(obj, function(i, value){
// Check the checkbox with the corresponding value
$('input[type="checkbox"][value="'+value.service+'"]').attr('checked', true);
});
});
});
</script>
Contents op post.api.php
<?php
// only access this if there is value for api being posted to it
if(isset($_POST['api'])){
// only access this if $_POST['api'] = getServices
if($_POST['api'] == 'getServices'){
// Create and array to store the data
${'Response'} = array();
// Get the users id
${'Business ID'} = $_POST['business_id']; // you should clean this to avoid sql injection
// Iterator
${'Iterator'} = 0;
// Query your database and return the values of the services that you stored during registration.
$sql = "SELECT `service_id_fk` FROM `business_services_offered` WHERE `business_id` = '".${'Business ID'}."'"; // your WHERE statement should include the user id sent here in ${'User ID'}
$query = mysql_query($sql);
// Do your while loop with your query results
while($row = mysql_fetch_assoc($query)){
// store our service value
${'Response'}[${'Iterator'}]['service'] = $row['service_id_fk'];
// increment our iterator
${'Iterator'}++;
}
// return the json to the posting file
echo json_encode(${'Response'});
}
exit;
}
?>
Or you can do this:
${'Business ID'} = "1";
// query the service table
$query = mysql_query('SELECT `a`.`service_id`,`a`.`service_name`, `b`.`record_id` FROM `services` `a` LEFT JOIN `business_services_offered` `b` ON `b`.`service_id_fk` = `a`.`service_id` WHERE `b`.`business_id` = "'.${'Business ID'}.'"');
while($row = mysql_fetch_assoc($query)){
if($row['record_id'] != NULL){
$checked = ' checked="checked"';
} else {
$checked = '';
}
${'The Form'} .= '<label>
<input type="checkbox" name="CheckboxGroup[]" value="'.$row['service_id'].'" id="CheckboxGroup_0"'.$checked.' />'.$row['service_name'].'</label>
<br />';
}
${'The Form'} = '</form>';
echo ${'The Form'};
I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.
I'm writing a jQuery mobile page (with PHP) that populates a select element and it's option tags with "items" from a table in a MySQL database (the table contains id, items, cost). Using the commonly cited mysql_query and while mysql_fetch_assoc method to echo out the options this works fine. Stripping to the bare code:
<?php
$itemQuery = mysql_query("SELECT shortDesc FROM `items` ORDER BY shortDesc");
?>
<label for="item" class="select">Item:</label>
<select name="item" id="item" data-native-menu="false">
<option>Select Item:</option>
<?php
while($temp = mysql_fetch_assoc($itemQuery))
{
echo "<option value='".$temp['shortDesc']."'>".$temp['shortDesc']."</option>";
}
?>
</select>
I'd like however to be able to update the input element below that called "cost" with the actual item's cost from the MySQL table, when the user selects an item from the list, and I'm uncertain how to do that using jQuery/PHP/MySQL. The cost input field:
<label for="cost">Cost:</label>
<input type="text" name="cost" id="cost" value="" placeholder="Cost (£)"/>
I'm also not sure if we can get the cost value somehow from the results already returned in $itemQuery (by changing the SELECT to shortDesc,cost) saving another database query, or whether we do have to query the database again to perform a select where the user's selection = shortDesc.
I suspect in different forms, this is a common requirement for developers; essentially grabbing some information from a database based on a user's selection / interaction. I have looked on Google and searched here but I am not sure if I'm using the right search terms to find what I suspect will already be answered elsewhere!
Help greatly appreciated as always.
You could do:
1) Loop through your query results and write your options and some javascript (i use an Associative Array)
<?php
$result = mysql_query("SELECT shortDesc,costs FROM items ORDER BY shortDesc");
$options = '';
$javascript = '';
while ($row = mysql_fetch_assoc($result))
{
$options .= '<option value="'.$row['shortDesc'].'">'.$row['shortDesc'].'</option>';
$javascript .= '\''.$row['shortDesc'].'\' : \''.$row['costs'].'\',';
}
?>
2) write your html and javascript:
<select id="yourselect">
<option>select</option>
<?=$options?>
</select>
<label for="cost">Cost:</label>
<input type="text" name="cost" id="cost" value="" placeholder="Cost (£)"/>
3) write some javascript to update your input field:
<script>
var costs = {<?=$javascript?>};
$(function() {
$('#yourselect').change(function() {
cost = costs[$('#yourselect').val()];
$('#cost').val(cost);
});
});
</script>