Inserting values into database from form with drop downs - php

I'm trying to insert values input from the user in a form into my database.
I am trying to create 2 drop down lists, with the first deriving the options for the second. For example the first drop down list for Faculty, with the second drop-down list containing the schools within the selected faculty.
I am also then wanting to insert the gathered information into my database however I can focus on that after getting the drop-down's correct first.
My register page is on one page with the getSchool.php on a different file, I have a feeling the connection between the two could be my issue.
The register.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM faculty");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Faculty & School</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
type="text/javascript"></script>
<script>
function getFaculty(val) {
$.ajax({
type: "POST",
url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
}
});
}
function selectFaculty(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Faculty:</label><br/>
<select name="faculty" id="facultyList" class="demoInputBox"
onChange="getFaculty(this.value);">
<option value="">Select Faculty</option>
<?php
foreach($results as $faculty) {
?>
<option value="<?php echo $faculty["facultyID"]; ?>"><?php echo
$faculty["facultyName"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
Below is the getSchool.php which gets all the schools
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
<?php
}
}
?>
Thanks in advance for any feedback and help.
Simon

url: "getFaculty.php",
data:'facultyID='+val,
success: function(data){
$("#schoolList").html(data);
Where is the #schoolList element ? Why getFaculty.php? Should it not be getSchool.php ?

First, just to re-iterate what was already mentioned, update your getFaculty() to get getSchool() and make sure it points to getSchool.php.
Now, you need to create a div following your first drop-down with an id schoolList.
<div class="row" id="schoolList"></div>
Now, update your getSchool.php so that it generates the full form/selection. Something along the lines of:
<?php
include('dbConnect.php');
if(!empty($_POST["facultyID"])) {
$queryStr=("SELECT * FROM school WHERE facultyID = '" . $_POST["facultyID"]
. "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<label>Schools:</label><br/>
<select name="schoolSelect" id="schoolSelect" class="demoInputBox">
<option value="">Select School</option>
<?php
foreach($results as $school) {
?>
<option value="<?php echo $school["schoolID"]; ?>"><?php echo
$school["schoolName"]; ?></option>
Once you've got those ideas down, you'll have to make sure you have the full flow of your page the way you want it. Then follow similar standards for posting any inputs to the php page you use for database manipulation.
As noted in earlier posts, this solution still leaves you vulnerable to injection. That's for another post, another day.

Related

Dynamic dropdown list with PHP & MYSQL

I have been trying to create a form with dynamic dropdown list fetching data from MYSQL. My database is fine without errors.
The first category of dropdown is working fine but I am wondering why my 2nd dropdown is not working. I just cant trace any error in the code and yet this is happening. here's my code:
Code for dynamic dropdown form :
<?php
include_once "connection.php";
?>
<!DOCTYPE html>
<html>
<head>
<title>Dropdown Ajax</title>
</head>
<body>
<div class="country">
<label>Country</label>
<select name="country" onchange="getId(this.value);">
<option value="">Select Country</option>
//populate value using php
<?php
$query = "SELECT * FROM country";
$results=mysqli_query($con, $query);
//loop
foreach ($results as $country){
?>
<option value="<?php echo $country["cid"];?>"><?php echo $country["country"];?></option>
<?php
}
?>
</select>
</div>
<div class="city">
<label>City</label>
<select name="city" id="cityList">
<option value=""></option>
</select>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-
16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous">
</script>
<script>
function getId(val){
//We create ajax function
$.ajax({
type: "POST",
url: "getdata.php",
data: "cid="+val,
success: function(data){
$(#cityList).html(data);
}
});
}
</script>
</body>
</html>
Database connection code :
<?php
$con = mysqli_connect("localhost", "root", "kensift", "tuts");
//Check connection
if(mysqli_connect_errno()){
echo "Failed to connect:".mysqli_connect_errno();
}
?>
Code for 2nd dynamic dropdown :
<?php
include_once "connection.php";
if (!empty($_POST["cid"])) {
$cid = $_POST["cid"];
$query="SELECT * FROM city WHERE cid=$cid";
$results = mysqli_query($con, $query);
foreach ($results as $city){
?>
<option value="<?php echo $city["cityId"];?>"><?php echo $city["city"];?>
</option>
<?php
}
}
?>
These three code parts are in different files.
I think your code is correct except forgot the quotations id "#cityList" .
It should be
$("#cityList").html(data);
I think your problem might be here:
foreach ($results as $country){
?>
<option value="<?php echo $country["cid"];?>"><?php echo
$country["country"];?></option>
<?php
}
Try and use this instead:
foreach ($results as $country){
echo'<option value="'.$country["cid"].'">'.
$country["country"].'</option>';
}

How do I selectively add 3rd select box or relabel & redirect to a 2nd select box?

I have a form where the 1st select box is required. Depending on the selection, a different table will be used as a source for the query to populate a 2nd select box. Then depending also on the 1st selection a 3rd select box may or may not be necessary. I have designed the form to initially show 3 select boxes, but the user would have to know to skip the 2nd select box in some cases. This is confusing at the least. As an example:
If None is selected for Company, then both the Cemetery & Section select boxes would have to shown (Section being dependent on Cemetery selected). If XYZ Company is selected, then only the Section select box would need to be seen / selected (as the Cemetery is Company specific):
<script>
function getCemetery(val) {
$.ajax({
type: "POST",
url: "get_cemetery.php",
data:'company_name='+val,
success: function(data){
$("#cemetery-list").html(data);
}
});
}
Here is the code of the form:
<body>
<div class="frmDronpDown">
<div class="row">
<label>Company:</label><br/>
<select name="company" id="company-list" class="demoInputBox" onChange="getCemetery(this.value);">
<option value="">Select Company</option>
<?php
foreach($results as $company) {
?>
<option value="<?php echo $company["name"]; ?>"><?php echo $company["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Cemetery:</label><br/>
<select name="cemetery" id="cemetery-list" class="demoInputBox" onChange="getSection(this.value);">
<option value="">Select Cemetery</option>
<?php
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Section:</label><br/>
<select name="section" id="section-list" class="demoInputBox">
<option value="">Select Section</option>
</select>
</div>
</div>
</body>
And here is the additional php code the is called within the script:
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["company_name"])) {
if (($_POST["company_name"]<>"None") && ($_POST["company_name"]<>"Other")) {
$sql="SELECT name, available FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$result = mysql_query($sql) or die ( mysql_error());
$row = mysql_fetch_row($result);
$section = $row[0]; // best choice to use if auto fill
$query="SELECT * FROM compsections WHERE cname = '".$_POST["company_name"]."'"." ORDER by available desc;";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Section</option>';
}else{
$query ="SELECT * FROM cemeteries";
$results = $db_handle->runQuery($query);
echo '<option value="">Select Cemetery</option>';
}
foreach($results as $cemetery) {
?>
<option value="<?php echo $cemetery["name"]; ?>"><?php echo $cemetery["name"]." - ".$cemetery["available"]; ?></option>
<?php
}
}
?>
Edit:
Thank you for telling me about .hide and .show. I have looked up examples and what I can find uses a button click. Would you show an example of using them in an php if..else?
Thank you in advance.
Russ
I used the following:
<script>
function wholesection() {
$( "#whole-section" ).slideUp( "fast", function() {
});
}
</script>
AND
echo '<script>',
'wholesection();',
'</script>'
;

Empty query result

in a web form there are two drop-down lists. The second list items should change dynamically depending on the value selected on the first drop-down list.
This is how am I trying to do it:
index.php:
...
<script>
function getClient(val) {
$.ajax({
type: "POST",
url: "get_contacts.php",
data:'client_id='+val,
success: function(data){
$("#contacts-list").html(data);
}
});
}
</script>
...
<div class="form-group">
<label for="mto_client" class="col-sm-2 control-label">MTO Client</label>
<div class="col-sm-10">
<select name="mto_client" id="clients_list" onChange="getClient(this.value)">
<option value="">Select a Client</option>
<?php
do {
?>
<option value="<?php echo $row_RSClients['id_client']?>" ><?php echo $row_RSClients['client_name']?></option>
<?php
} while ($row_RSClients = mysql_fetch_assoc($RSClients));
?>
</select>
</div>
</div>
<div class="form-group">
<label for="mto_client_contact" class="col-sm-2 control-label">MTO Client Contact</label>
<div class="col-sm-10">
<select name="state" id="contacts-list">
<option value="">Select Client Contact</option>
</select>
</div>
</div>
get_contacts.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["client_id"])) {
$query ="SELECT * FROM tb_client_contacts WHERE contact_client_id = '" . $_POST["client_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Client Contact</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id_client_contact"]; ?>"><?php echo $state["contact_name"]; ?></option>
<?php
}
}
?>
There are objects on the table tb_clients_contact that meet the condition, but the second drop-down list doesn't show any objects.
Any help is welcome.
Instead of
$("#contacts-list").html(data);
It should be
$('#contacts-list').empty().append(data);
empty() will clear first the options inside the contacts-list select field, then append() will insert the options from the result of your AJAX.
You can also look at the console log for errors. If you are using Google Chrome, hit F12 to display the console log.

Show/hide select values based on previous select choice

I have 2 select's inside a form. The second select has about 2000 lines in total coming out of my mysql table. One of the column into that mysql has 1 of the values used into the first select. I want to be able to filter on that value when it is selected into the first select, so that it only shows these articles.
code now:
<div class="rmaform">
<select name="discipline" class="discipline">
<option value=" " selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article">
<?php
$articleselect = $dbh->prepare('SELECT * FROM articles');
$articleselect->execute();
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
</select>
I think i have to use Javascript for it but how do you combine PHP and Javascript? And what would be the best way to make the filter work?
jQuery for the change event and AJAX
$(document).ready(function(e) {
$('select.discipline').change(function(e) { // When the select is changed
var sel_value=$(this).val(); // Get the chosen value
$.ajax(
{
type: "POST",
url: "ajax.php", // The new PHP page which will get the option value, process it and return the possible options for second select
data: {selected_option: sel_value}, // Send the slected option to the PHP page
dataType:"HTML",
success: function(data)
{
$('select.input-article').append(data); // Append the possible values to the second select
}
});
});
});
In your AJAX.php
<?php
if(isset($_POST['selected_option']))
$selected_option=filter_input(INPUT_POST, "selected_option", FILTER_SANITIZE_STRING);
else exit(); // No value is sent
$query="SELECT * FROM articles WHERE discipline='$selected_option'"; // Just an example. Build the query as per your logic
// Process your query
$options="";
while($query->fetch()) // For simplicity. Proceed with your PDO
{
$options.="<option value='option_value'>Text for the Option</option>"; // Where option_value will be the value for you option and Text for the Option is the text displayed for the particular option
}
echo $options;
?>
Note: You can also use JSON instead of HTML for much simplicity. Read here, how to.
First give both of the selects an unique ids...
<div class="rmaform">
<select name="discipline" class="discipline" id="discipline">
<option value="" selected></option>
<option value="access">ACCESS</option>
<option value="inbraak">INBRAAK</option>
<option value="brand">BRAND</option>
<option value="cctv">CCTV</option>
<option value="airphone">AIRPHONE</option>
<option value="perimeter">PERIMETER</option>
</select>
</div>
<div class="rmaform">
<select name="article" class="input-article" id="article">
<option value="" selected></option>
</select>
Now you can use jQuery Ajax call to another file and get the HTML Response from that file and Populate in the select field with id="article" like this...
<script type="text/javascript">
$(document).ready(function(){
$("#discipline").change(function(){
var discipline = $(this).val();
$.post(
"ajax_load_articles.php",
{discipline : discipline},
function(data){
$("#article").html(data);
}
)
});
});
</script>
Now create a new file like ajax_load_articles.php... in the same directory where the html file exists... You can place it anywhere but then you have to change the $.post("url", the url to the ajax submission.
Contents of ajax_load_articles.php :
<?php
$discipline = $_POST["discipline"];
$articleselect = $dbh->prepare("SELECT * FROM articles WHERE colname = '{$discipline}'");
$articleselect->execute();
echo '<option value="" selected></option>';
while($articlerow = $articleselect->fetch(PDO::FETCH_ASSOC)){
?>
<option value="<?php echo $articlerow['a_code'];?>"><?php echo $articlerow['a_code'];?> <?php echo $articlerow['a_omschr_nl'];?></option>
<?php
}
?>
Now when ever you will change the select of the first select field an Ajax call will take place and the data of the second select field will automatically adjust to related data selected in the first select field.
This is an example where you can select the college specific to the state ..
Form.php
// your code for form ...
// select box for state starts
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">State</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="statename" id="stateid">
<option value="">---- Select ----</option>
<?php
$state=sql::readResultArray("Your Query To select State`");
foreach($state as $s){
?>
<option value="<?php echo $s?>"> <?php echo $s ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 col-md-2 control-label">Colleges</label>
<div class="col-lg-10 col-md-10">
<select class="form-control input-sm" name="mycollegename">
<option value="">--- Select --- </option>
</select>
</div>
</div>
// further code for from in form.php..
Script to find the state and then pass the value to find the respective colleges in that state
<script>
$(document).ready(function(e) {
$('#stateid').change(function()
{ ids=$('#stateid').val();
$.get('mycollege.php', {type:ids} ,function(msg){
$('select[name="mycollegename"]').html(msg);
});
});
});
</script>
Call this file through ajax .. Code on this file
mycollege.php
<?php
require('db.php'); // call all function required, db files or any crud files
$type=$_GET['type'];
if(!empty($type)){
$r=sql::read("Your Query To call all teh college list");
?>
<select name="mycollegename">
<option value="">Select One</option>
<?php
foreach($r as $r){
echo "<option value=\"$r->collegename\">$r->collegename </option>";
}
?>
</select>
<?php }else{ ?>
<select name="mycollegename">
<option value="">Select State</option>
</select>
<?php } ?>

drop-down menu with php function

I've already created my html form with a drop-list menu of 5 selections
I want a selected option from the drop-list to call php function that will echo a selected option to the screen
<label>Fruits</label>
<select name="Fruits">
<option value="Ap">Apple</option>
<option value="BN">Banana</option>
<option value="OR">Orange</option>
For example, here is your html code
<html>
<head></head>
<title>Static Dropdown List</title>
<body bgcolor="pink">
Employee List :
<select>
<option value="Select">Select</option>}
<option value="Moyed">Moyed Ansari</option>
<option value="Asad">Asadullah</option>
<option value="Usman">Usman Ali</option>
</select>
</body>
</html>
Now You will use the above table in the dropdown list using the following code.
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<BODY bgcolor ="pink">
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
Employee List :
<select Emp Name='NEW'>
<option value="">--- Select ---</option>
<?
mysql_connect ("localhost","root","");
mysql_select_db ("company");
$select="company";
if (isset ($select)&&$select!=""){
$select=$_POST ['NEW'];
}
?>
<?
$list=mysql_query("select * from employee order by emp_id asc");
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<? echo $row_list['emp_id']; ?>"<? if($row_list['emp_id']==$select){ echo "selected"; } ?>>
<?echo $row_list['emp_name'];?>
</option>
<?
}
?>
</select>
<input type="submit" name="Submit" value="Select" />
</form>
</body>
php is on the server side
where as all the html is on the user side..
if you want to echo the selected option, then you have to send the selected option to the server side using Ajax Request or using some other technique like POST a form.
// using jquery you can get your selected value
<script>
var selected_value = $("#idOfTheSelectTag").val();
// or you can also do
var selected_value = $("#idOfTheSelectTag :selected").text();
// now you can post it to the php page using AJAX where you can echo it
$.post('page_name.php', {SELECTED_VALUE : selected_value}, function(data){
// on the server side in page_name.php file if you echo the value then it will be returned in the data object in the function
});
</script>

Categories