Select from database in a multiselect and then insert as an array - javascript

I used this code to select classes for students from the database in a dropdown. It appeared correctly. Then I when I realized that I actually want to select more than one class for a student, I added multiple. It showed as a multiple but still inserts only one value in database table.
<?php
require_once('../config.php');
$class_result = $conn->query('select * from class');
?>
<label for="exampleFormControlTextarea1">Class</label>
<select class="form-control" name="class[]" id="class" multiple>
<option value=""></option>
<?php
if ($plot_type_result->num_rows > 0) {
// output data of each row
while ($row = $plot_type_result->fetch_assoc()) {
?>
<option value="<?php echo $row["class"]; ?>">
<?php echo $row["class"]; ?>
</option>
<?php
}
}
?>
</select>
Now I want this select class to be a multi select. If I add multiple it becomes a multiple but doesn't really inserts the multiple values I select. Only selects the last selected from the database and inserts it as a single one. How can I achieve multi select and actually pass it as an array to the database with more than one value?

$classDatas= implode(", ", $datas);
You can try to save the array in a single column by converting it to text with implote.

Related

Filter Dropdown Based on Another Dropdown Selection

I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>

Storing Two Values in Table from Option Menu

I have a form with an option menu with Staff_Names that gets its data from "Staff" table:
<select class="form-control" name="Name" id="Name">
<option value="">select staff</option>
<?php do { ?>
<option value="<?php echo $row_Staff['Staff_Name'] ?>">
<?php echo $row_Staff['Staff_Name']?></option>
<?php } while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
The "Staff" table also has the staff member's Email. The form elements are inserted into a new table called "Training". I would like to select the Staff_Name from the option menu and insert the Staff_Name and Email in separate fields in the Training table. I have tried explode("-", $_POST['Name'] method from How to post two values in an option field? but feel there has to be a more efficient way. I don't want to continue to explode every time I need to echo in subsequent pages. Also, explode only works in this method by exploding on another page. Would like to store both fields from form when inserting into Training table. Does anyone have an efficient method?

How to make input selected after the refresh the page?

How to display form inputs without loosing data entered before refresh the page? I mean After refresh my page I want to display all the values entered in forms.
I have 2 inputs One is select option and one is text.
<input type="text" name="worked_month" value="<?php echo $_SESSION['worked_month']; ?>" />
<select name="sex">
<option value="">Select Sex</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
I am using following PHP code to display text enter before I refresh the page
isset($_POST['worked_month'])?$_SESSION['worked_month'] = $_POST['worked_month']:$_SESSION['worked_month']="";
It works fine but don't know how to select the option that are selected before refresh. But I don't have to always select same default value. User can select any value
Explanation. For each option, check if the post variable matches the value and then use selected attribute to select the matched option.
<select name="sex">
<option value="">Select Sex</option>
<option <?php echo isset($_POST['sex']) && $_POST['sex']=='male'? 'selected="selected"' = '' ?> value="male">Male</option>
<option <?php echo isset($_POST['sex']) && $_POST['sex']=='female'? 'selected="selected"' = '' ?> value="female">Female</option>
</select>
To select option you have to use PHP dynamic variable.Check this reference
<?php
$sex = $_SESSION['sex'];
${$sex.'_checked'} = "selected";
?>
<select name="sex">
<option value="">Select Sex</option><option value="male" <?php echo $male_checked; ?> >Male</option><option value="female" <?php echo $female_checked; ?>>Female</option></select>
Dynamic variable: automatic convert your selected value into variable whose value is "selected".
I just made something like that saving the values at Local Storage and then retrieving them:
//Saving the input values at local storage
var temp = [];
$('.keep-values').each(function(){
temp.push({
id:$(this).attr('id'),
value:$(this).val().trim(),
checked:$(this).is(':checked')
});
});
localStorage['valuesCache'] = JSON.stringify(temp);
Then i retrive the values and i populate the fields:
//Retrieving the values from local Storage and populating the inputs
var tmp = JSON.parse(localStorage['valuesCache']);
for(i in tmp) {
$('#'+tmp[i].id).val(tmp[i].value);
if(tmp[i].checked){
$('#'+tmp[i].id).attr('checked','');
}
}
I think thats a good start for your final solution, read more about Local Storage

Insert from combo box using php

I am populating a combo box from database, the problem is when I select an item from the combo box and try to save to another table in the database it picks the record ID column instead of the item itself.
this is the how am populating the combo box.
<label>State</label>
<select name="state" class="state" onChange="display(this.value)" width="142" style="width: 142px">
<option value="" selected="selected">-- Select State --</option>
<?php
$query="select * from tbl_state";
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['state_name']; ?></option>
<?php
}
?>
</select>
<div id="show_city" style="position: relative" height:5px;>
<label>LGA</label>
<select name="city" class="lga" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
</select>
</div>
</p>
Database connection
$state = $_POST['state'];
$city = $_POST['city'];
$sql="INSERT INTO members (state, city)
VALUES ('$state', '$city')";
NB. am using javascript to populate the combo box.
When you submit a form, only the field name along with its value will be sent. In your case, when the user select the state and press submit, the row id will be sent as you specify the row id at the option value tag.
Either you can use <option value="<?= $row['state_name'] ?>"> ... </option>" and then get the state name ini php directly:
$state = $_POST['state'];
or leave the populating code as is now and get the state name by querying database using the record id.
$state_id = intval($_POST['state']);
$city_id = intval($_POST['city']);
$sql = "SELECT `state_name` FROM tbl_state WHERE id=$state_id";
$query_result = mysql_query($sql) or mysql_error();
$state = mysql_result($query_result, 0);
echo $state;
getcity.php
<?php
$con=mysql_connect('localhost','root','') or die('Mysql not connected');
mysql_select_db('thriftdb',$con) or die('DataBase not connected');
$state_id=$_REQUEST['state_id'];
$query="select * from lga where state_id='$state_id'";
?>
<label>LGA</label>
<select name="city" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
<?php
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['lga_name']; ?></option>
<?php
}
?>
</select>
database structure is as follows
'lga' table has...
lga_id --- state_id --- lga_name
'state' table has
state_id --- state_name
When a form sends the selected item of a combo, it sends the value of the option selected, not the text. If you want to send the text, add a hidden input for every combo, then in the onclick event of the combos, call a function that populates the text to the hidden input.
selectState = function() {
$('#hiddenInputField').val($("select[name='state'] option:selected").text());
}
Then in the server side you must get the value of the input hidden field instead of the select field.

Javascript: Sustaining Selected Index of a ComboBox on Search

I have a problem with my javascript. First of all here is my code partitions:
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<option value="0">2013</option>
<option value="1">2012</option>
<option value="2">2011</option>
</select>
function searchClicked() {
var operationField = document.getElementById("<%=FeedbackReportCtrl.PARAM_OPERATION%>");
operationField.value = "<%=FeedbackReportCtrl.OPERATION_SEARCH%>";
var yearFilter = document.getElementById("<%=FeedbackReportCtrl.PARAM_YEARFILTER%>");
yearFilter.value = document.getElementById("yearCombo").options[document.getElementById("yearCombo").selectedIndex].text;
var mainForm = document.getElementById("main");
mainForm.submit();
}
Here what goes wrong is the following;
For example, when I choose the year 2011 from the combo box and then hit the search button, it brings me the desired results;however, the selected index of the box returns back to 2013. How can I sustain my selection after search function?
The issue you have isn't a javascript one. When you submit a form you refresh the whole page, removing any client-side (user or javascript) adjustments to it.
It should be set by the php/java that is generating the page you post your form to, to set a selected="selected" or relevant, based on the value you just posted.
In php this would be
if($_POST['year'] == '2013') echo ' selected="selected"';
In java or jsp there are similar ways of doing this. Javascript itself could do the same probably.
Submitting the form refreshes the page (unless done via AJAX), thus returning to the default selected value, i.e the first one.
To overcome this you need to send along with the form the chosen year - assuming that you are self-submitting - and explicitly mark this year as the selected option.
In PHP Your code would then be something like:
<?php $year = $_POST['year']; ?>
<select class="inputTxt" style="width: 120px;" id="yearCombo" name="yearCombo">
<?php for ($i=2013;$i>2010;$i--): ?>
<option value="<?php echo $i; ?>" <?php if ($year==$i) echo "selected"; ?> >
<?php echo $i; ?>
</option>
<?php endfor; ?>
</select>

Categories

Resources