Populating the select input field with mysql data - php

I have created a main drop down list and with jquery I can choose the number of drop down menus to display. Done very simply by a for loop. The main dropdown list to choose how many drop downs to display is statically populated and I am trying to dynamically populate the drop downs being displayed with data in mysql database. In the php side I am using a while loop to populate each select box. I am not getting any results being displayed. SITE
<script type="text/javascript">
$(document).ready(function () {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'"><option value="">--- Select ---</option>"'
<?php
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$course_query = "SELECT course_id, course_name FROM course ";
if($result = mysqli_query($mysqli, $course_query)) {
while ($idresult = mysqli_fetch_row($result))
{
$course_id = $idresult[0];
$course_name = $idresult[1];
echo'<option value="' . $course_id . '">' . $course_name . '</option>';
}
}
?>
'"';
content += '</select><br /><div><br />';
}
$('#course_catalog').html(content);
}
});
</script>

You need to echo a javascript line to start with, instead of echoing directly...
echo 'content += \'<option value="' . $course_id . '">' . $course_name . '</option>\';';

Related

how to show another dropdown box depend on dropdown box value

please i need help
i need to do specail command
when some value selected then show another dropdown box
my first dropdown box is in php
and he is my code :
$conn = mysqli_connect("localhost", "root",
"", "phoneunlock" )
or die("Cannot connect to database:" .
mysqli_connect_error($conn));
echo "<select name='selectedValue' class= 'dropdown' >";
echo '<option value="">'.'Please Select Service'.'</option>';
$sql = "SELECT id, manufacter FROM product";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{ echo "<option value='" . $row['manufacter']. "'>" . $row['manufacter'] . '</option>';
}
echo '</select>';
and know i need some command like this :
if dropdown box selected = value then
do this
end if
sow please can any one help me
if you mean like chained combobox. try using jQuery like this :
$('#yourcomboid').on('change', function() {
var id = $(this).val();
$('#youranothercombo').empty();
$.ajax({
url: 'your-route-to-get-data/' + id,
success: function(data) {
$('#youranothercombo').empty();
for(var i = 0; i < data.length; i++) {
var item = data[i];
$('#youranothercombo').append($('<option></option>').val(item.column-name).text(item.column-name));
}
}
});
});
Hope this code works.

MySQL Select based on drop down value

I have the following code:
<?php
session_start();
include_once("config.php");
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
echo '<select name="dropdown" value=""><option value="">Dropdown</option>';
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
echo "</select>";
?>
the values of the drop down box are filled from the database.
I was wondering if theres a way to have a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table?
any information will help!
Thanks
Ok, resontant81, you want to fill a table depending on the option selected, next code does exactly what you want, the explanation comes just after :
<html>
<head>
<title>My list</title>
<script type="text/javascript">
//----------------------------------------------------------------
// SENDS SELECTED OPTION TO RETRIEVE DATA TO FILL TABLE.
function send_option () {
var sel = document.getElementById( "my_select" );
var txt = document.getElementById( "my_option" );
txt.value = sel.options[ sel.selectedIndex ].value;
var frm = document.getElementById( "my_form" );
frm.submit();
}
//----------------------------------------------------------------
</script>
</head>
<body>
Click on any option
<br/>
<select id="my_select" onchange="send_option();">
<option>Select an option</option>
<?php
//----------------------------------------------------------------
// LIST FILLED FROM DATABASE (ALLEGEDLY).
for ( $i = 0; $i < 5; $i++ )
{ $text = chr($i+65) . chr($i+65) . chr($i+65);
echo "<option value='" . $text . "'>" . $text . "</option>";
}
//----------------------------------------------------------------
?>
</select>
<br/>
<br/>
<table>
<?php
//----------------------------------------------------------------
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
for ( $i = 0; $i < 4; $i++ ) // DISPLAY ROWS.
{ echo "<tr>";
for ( $j = 0; $j < 6; $j++ ) // DISPLAY COLUMNS.
echo "<td>" . $_POST["my_option"] . "</td>"; // DISPLAY OPTION.
echo "</tr>";
}
else echo "<tr><td>Table empty</td></tr>";
//----------------------------------------------------------------
?>
</table>
<!-- FORM TO SEND THE SELECTED OPTION. -->
<form method="post" action"01.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
</body>
</html>
To make things easier for you (and for me), I am not using a database, all you have to do is copy-paste previous code to a text file, rename it "01.php" (because that's the action of the form, you can change it), and run it in your browser, is ready to use.
The dropdown is filled from database (in this case, with letters), when an option is selected the page reloads with the selected option and fills the table.
You said: "a select statement that will run when a user clicks on one of the options in the drop down menu and then populate the results in a table". This select statement you want you must put it right after the line :
if ( IsSet( $_POST["my_option"] ) ) // IF USER SELECTED ANY OPTION.
So your select statement will take the selected option from $_POST and use it to retrieve the right data and display it.
Let me know if it helps you.
This is the code to fill the dropdown, it's my code with yours combined:
// LIST FILLED FROM DATABASE (ALLEGEDLY).
$query = "SELECT Category FROM books";
$result = mysqli_query ($mysqli, $query);
while ( $row = mysqli_fetch_array($result) )
echo "<option value='" . $row['Category'] . "'>" . $row['Category'] . "</option>";
Next edit is to fill the table. Change the query for the right one if it's not right :
// TABLE FILLED FROM DATABASE ACCORDING TO SELECTED OPTION.
$query = "SELECT Category FROM books where category like '" . $_POST["my_option"] . "'";
$result = mysqli_query ($mysqli, $query);
while( $row = mysqli_fetch_array($result) )
echo "<tr>" .
"<td>" . $row['book_name'] . "</td>" .
"<td>" . $row['author'] . "</td>" .
"<td>" . $row['Category'] . "</td>" .
"</tr>";
I'm assuming $mysqli is your db connection and it's made through config.php. I'm also assuming that category is a column name in the books table. It is up to you to sanitize and validate the user input. This is simply an example to get you started.
page.php ....
<?php
session_start();
include_once("config.php");
function categories() {
global $mysqli;
$result = "";
$stmt = "SELECT Category FROM books GROUP BY Category";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
$result .= '<option value="' . $row['Category'] . '">' . $row['Category'] . '</option>';
}
mysqli_free_result($sql);
mysqli_close($mysqli);
return $result;
}
IF (isset($_POST['ThisForm'])) {
$category = htmlspecialchars(strip_tags(trim($_post['dropdown'])));
$stmt = "SELECT * FROM books WHERE category ='$category'";
$sql = mysqli_query ($mysqli, $stmt);
while ($row = $sql->fetch_array(MYSQLI_BOTH))
{
// do something with result
}
// free result and close connection
mysqli_free_result($sql);
mysqli_close($mysqli);
}ELSE{
// base form
echo '<form action="page.php" name="something" method="post">';
echo '<select name="dropdown" value=""><option value="">Dropdown</option>'.categories().'</select>';
echo '<input type="submit" name="ThisForm" value="submit" />';
echo '<form>';
}
?>

dynamic selected option using variables from mysql

After finally getting this to work, I thought I'd post it in case it maybe
I was having trouble working to populate a few sets of dropdown select tags.
I had researched a number of similar submissions and solutions, but I still couldn't find the answers I'd been looking for.
#Ronser had helped me to test through my queries, which lead me to learning more about how the arrays actually worked. I realised I needed to go back and to update the access column in TABLE 1 to access_id. (I should've indexed these originally).
Table 1: app_generalData
app_id,
title,
status_id,
category_id,
tags,
access_id
Table 2: app_access
access_id,
access_title
Desired result(s):
Objective 1: Show/echo the selected option (stored in app_access table)
Objective 2:
Build these queries with variables to allow for easy updating for adding new dropdowns.
Resulting HTML:
<select name="access"><option "">Global</option>\n<option " selected ">Corporate</option>\n<option "">Local Site</option>\n</select>
Code:
<?php
//connect to the database
require_once('connectvars.php');
// global variable for this populating this dropdown
$dropdown = "access";
$before_var = "app_";
$column1= $before_var.$dropdown;
$after_var = "_title";
$column2= $dropdown.$after_var;
$id_var= "_id";
$dropdown_table_id= $dropdown.$id_var;
$optionsList = array();
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.');
echo '<select name="' . $dropdown . '">';
// See if we're viewing a selected app or are we creating a new app
if (isset($_GET['app_id'])) {
// print_r($_GET); // GET is Successful
// 'if' [app_id] is appended in the url
// STEP 1: Get the stored value of the SELECTED from mysql
// Get "selected item" (id) from app_generalData (table) with the "selected app" (id)
$option = "SELECT ".$dropdown_table_id." FROM app_generalData WHERE app_id ='" . $_GET['app_id'] . "'";
// submit the select statement
// Get & store the value of "selected" <option>
$selected_option = mysqli_query($dbc, $option)
or die(mysql_error());
$row_1=mysqli_fetch_array($selected_option);
// STEP 2: Build the SELECT input
// Set the array of data to populate dropdown list <option>s
$options = "SELECT * FROM ".$column1." ORDER BY ".$dropdown_table_id."";
// NOTE: print_r($options)...SELECT access_title FROM app_access ORDER BY access_id
$selected_options = mysqli_query($dbc, $options)
or die(mysqli_error());
$kk = 0; //initialize kk
while($row_2 = mysqli_fetch_array($selected_options)) {
$selected ='';
if($row_1["$dropdown_table_id"]==$row_2["$dropdown_table_id"]) {
$selected=' selected ';
}
$optionsList[$kk++] ='<option "' . $selected . '">' . $row_2["$column2"] . '</option>';
}
// Echo the <option>s
$optionCount = count($optionsList);
for($i=0;$i<$optionCount;$i++) {
echo $optionsList[$i].'\n';
}
}
else {
// Action 'if' no [app_id] is appended in the url
};
// close the last <select> tag
echo '</select>';
// close the last database
mysqli_close($dbc);
?>
Please try the following...
Check for the 'app_id'.
Print the sql query and run directly in your mysql.
If it returns no rows or error please verify the sql query.
try this...
$options = "SELECT ".$column2." FROM ".$column1." ORDER BY ".$dropdown_table_id."";
$kk = 0; //initialize kk
while($row = mysqli_fetch_array($options)) {
$selected ='';
if($selected_option==$row["$column2"]) {
$selected=' selected ';
}
$optionsList[$kk++] ='<option "' . $selected . '">' . $row["$column2"] . '</option>';
//try this change. or
echo '<option "' . $selected . '">' . $row["$column2"] . '</option>'; //print it here itself
}
print_r($optionsList);
<?php
//connect to the database
require_once('connectvars.php');
// global variable for this populating this dropdown
$dropdown = "access";
$before_var = "app_";
$column1= $before_var.$dropdown;
$after_var = "_title";
$column2= $dropdown.$after_var;
$id_var= "_id";
$dropdown_table_id= $dropdown.$id_var;
$optionsList = array();
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.');
echo '<select name="' . $dropdown . '">';
// See if we're viewing a selected app or are we creating a new app
if (isset($_GET['app_id'])) {
// print_r($_GET); // GET is Successful
// 'if' [app_id] is appended in the url
// STEP 1: Get the stored value of the SELECTED from mysql
// Get "selected item" (id) from app_generalData (table) with the "selected app" (id)
$option = "SELECT ".$dropdown_table_id." FROM app_generalData WHERE app_id ='" . $_GET['app_id'] . "'";
// submit the select statement
// Get & store the value of "selected" <option>
$selected_option = mysqli_query($dbc, $option)
or die(mysql_error());
$row_1=mysqli_fetch_array($selected_option);
// STEP 2: Build the SELECT "selected" and <options>
// Set the array of data to populate dropdown list <option>s
$options = "SELECT * FROM ".$column1." ORDER BY ".$dropdown_table_id."";
// NOTE: print_r($options)...SELECT access_title FROM app_access ORDER BY access_id
$selected_options = mysqli_query($dbc, $options)
or die(mysqli_error());
$kk = 0; //initialize kk
while($row_2 = mysqli_fetch_array($selected_options)) {
$selected ='';
// Compare access_id from table1 against access_id from table2
if($row_1["$dropdown_table_id"]==$row_2["$dropdown_table_id"]) {
$selected=' selected ';
}
$optionsList[$kk++] ='<option "' . $selected . '">' . $row_2["$column2"] . '</option>';
}
// Echo the <option>s
$optionCount = count($optionsList);
for($i=0;$i<$optionCount;$i++) {
echo $optionsList[$i].'\n';
}
}
else {
// Action 'if' no [app_id] is appended in the url
};
// close the last <select> tag
echo '</select>';
// close the last database
mysqli_close($dbc);
?>

How to get data from database and create a dynamic select?

Im trying to create a select which is dynamic, for example if there is 3 item in the database gift, then it will create 3 select with value from the database lecturer. This is the javascript to create the select when the user click the button add.
Now after the user have create 3 select and submit it, if the user wish to edit back the data, how can I do it ?
function addField(area,field,limit)
{
var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("select");
var last_item = all_inputs.length - 1;
var last = all_inputs[last_item].id;
if(document.createElement)
{
var li = document.createElement("li");
var input = document.createElement("select");
var opt = document.createElement("option")
input.id = field;
input.name = field;
opt.value = "NULL";
opt.textContent = "NO LECTURER";
li.id = "li"+last_item;
input.appendChild(opt);
li.appendChild(input)
$(document).ready(function()
{
$.ajax
({
type:"post",
url: "event/data.php",
success: function(data)
{
console.log(data);
$(input).append(data);
}
});
});
field_area.appendChild(li);
}
}
Here example of what I have create,
http://i.imgur.com/je1MchL.png
Here how it works
http://i.imgur.com/c4ICTWt.png
So basically in the database have 5 data, so what im trying to do is in the next page it will automatic create the exact 5 select. How can I do this?
Thanks
Create a function (useful for reuse)
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
and call it:
// $options : return array from DB
$curr = 'some_key';
$select_name = 'my_select';
echo create_select($select_name,$options,$curr);
A complete working example:
<?php
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('effone_db');
$query = mysql_query("SELECT * FROM settings");
while ($row = mysql_fetch_array($query)) {
$options[$row['option']] = $row['option_value'];
}
echo create_select('settings',$options,'100');
?>
Let's assume that $options holds the resulting query.
So what you must do is loop thru the items and echo them inside a <select> tag.
like:
<html>
<body>
<select name='nameUrSelectHere'>
<?php
foreach($options as $option){
echo "<option value='" . $option['column_one'] . "'>" . $option['column_two'] . "</option>" ;
}
?>
</select>
</body>
</html>

How to insert multiple values into database using php for loop

i have one textbox and one dropdown box in each row.
now i want to enter some date in text box and select some value in dropdown.
when i click it should get saved into database.
How can i do this?
here is my code
php insert code:
When i click submit this php code should
<?php
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
?>
drop down is generated dynamically
code:
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += "<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT language FROM languages;';
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='language' id='course'>";
echo "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['language'] ."'>" . $row['language']. "</option>";
}
echo "</select>";
?>";
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
the ui looks something like this...
Add name
for text box and select box like this
name="text_box"+i and name="select_box"+i. "i"
is value from counter in loop, for example if you have 100 New Moview you will have name for each text box like this text_box1, text_box2. ..... text_box100. You should on submit remeber the numbers of "New MovieS" and that is "i" and in php code just loop for each element and save them. In first iteration you will have $_POST[Fname1] and $_POST[language1], etc..
Add a line in your js which makes the inputs to print something along the lines of target.innerHTML = '<input name="RowCount" value="' + param + '" hidden />' then in your PHP use:
for ($i=0; $i < $_POST["RowCount"]; $i++) {
$query = sprintf("INSERT INTO movie ('movie_name', 'language') VALUES ('%s', '%s')",
mysqli_real_escape_string($_POST["Fname"]), // Escaping values before inserting.
mysqli_real_escape_string($_POST["language"]));
mysqli_query($con, $query);
}
in HTML Form: Set textbox and dropdown element name as same algorithm ElementName+RowNumber;
insert element for RowCount: <input type="hidden" name="RowCount" value="3">
in PHP: get values:
for($iRow=0;$iRow less $_POST['RowCount'];$iRow++) {
mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname'.$iRow]."','".$_POST['language'.$iRow]."');
}

Categories