dynamic selected option using variables from mysql - php

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

Related

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

php unable to display result webpage

I am having problem trying to get a web url working within php, I am basically getting a list of content displayed, the list content becomes a links to a result webpage (detail.php). I want to display the result webpage with more detailed info. on the same webpage with a back button to original list.
=====
my list webpage code
=====
$c = 0; //Variable to keep count of categories
$servicetype = '$brand'; //variable declaration last displayed servicetype.
$strSQL = "SELECT * FROM <tablename> ORDER BY serviceType, serviceName ASC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
//If the servicetype name has changed, display it and update the tracking variable
if ($servicetype != $row['serviceType']){
$servicetype = $row['serviceType'];
//If this isn't the first category, end the previous list.
if ($c>0) echo "</ul>";
echo '<h3>'.$row['serviceType'].'</h3><ul>'; // subheading & related content.
$c++;
}
$strName = $row['serviceName'];
$strLink = "<a href = 'detail.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
// Close the database connection
mysql_close();
?>
====
my detail.php code below
=====
$strSQL = "SELECT * FROM gu_service_cat WHERE id = " . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the detail data of the ID
echo '<h3>ID:</h3>' . $row['ID'] . ' ' . $row['guUrl'] . "</dd>";
echo "<dt>availability:</dt><dd>" . $row["availability"] . "</dd>";
}
//echo '<h3>'.$row['serviceType'].'</h3><ul>';
// Close the database connection
mysql_close();
?>
</dl>
<p>
Return to the list
I do see you incorectly using variable variables.
This is incorrect:
$servicetype = '$brand';
if ($servicetype != $row['serviceType'])
What you need to do is assign the variable $servicetype a string, in this case 'brand' and use that in the if statement:
$servicetype = 'brand';
if ($$servicetype != $row['serviceType'])
Notice the double dollar sign. Read more about Variable Variables.

How do i make a default value in a while loop

I have used a dropdown list which is populated with data from a database using a query but i can't seem to add a default value to the top of the list e.g. "Select Class". All DB data is being retrieved fine but cannot add any default title like Select Class.
function query(){
$classes = mysql_query("SELECT * FROM class") or die("Could not search!");
while ($row = mysql_fetch_array($classes)) {
echo '<option value="Select Class"'>' . $row['class_name'] . '</option>';
}
}
All help is much appreciated!
You need to add an <option> before you begin your loop.
function query(){
// This is the line you are missing
echo '<option>Select a class</option>';
$classes = mysql_query("SELECT * FROM class") or die("Could not search!");
while ($row = mysql_fetch_array($classes)) {
echo '<option value="Select Class"'>' . $row['class_name'] . '</option>';
}
}
Just echo out the default option before the while loop starts:
$classes = mysql_query("SELECT * FROM class") or die("Could not search!");
echo '<option value="">Select Class</option>';
while ($row = mysql_fetch_array($classes)) {
echo '<option value="Select Class"'>' . $row["class_name"] . '</option>';
}

Populating the select input field with mysql data

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>\';';

Display database fields as checkboxes

I'm trying to display all my database fields like radio buttons. For example I have this database fields :
hostess_id
hostess_name_en
hostess_surname_en
... etc ...
I want to display them as radio buttons, in order to select them, then display data information only for the selected buttons.
How can I do that?
I have something like this:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'db_up';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from hostess', $link);
while ($row = mysql_fetch_assoc($result)){
echo "<td><input type=\'checkbox\' name=\'hostess[]\' value=\'" . $row['hostess_id'] . "\'>" . $row['hostess_firstname_en'] . "<br />";
}
?>
With PDO, It will get all fields
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
With deprecated mysql_*
function mysql_field_array( $query ) {
$field = mysql_num_fields( $query );
for ( $i = 0; $i < $field; $i++ ) {
$names[] = mysql_field_name( $query, $i );
}
return $names;
}
// Example of use
$fields = mysql_field_array( $query );
Than you can loop through that array of field names and use the name with your check box.
Checkboxes need a unique name or they need to be an array. A checkbox array would be appropriate for what you're doing:
while ($row = mysql_fetch_assoc($result)){
echo "<input type='checkbox' name='hostess[]' value='" . $row['id'] . "' />" . htmlentities($row['hostess_surname_en']) . "<br />";
}
This will give you a list of checkboxes with the hostess surname next to each.
Now, when this form is submitted to a PHP script, you will be able to access the selected row id's with:
$selectedIds = $_POST['hostess']; // an array
$selectedIds is an array of the checked record ids.
I suggest using PDO or MySQLi for new code because the mysql_* library is deprecated.

Categories