MySQL Select based on drop down value - php

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

Related

PHP deleting variable after new form

In my code, I have two forms for users to select options. The first variable will save but as soon as the user submits the second form, the variable from the first form is no longer saved.
<div class = "school">
<h3>Please select the university you previously attended</h3>
<form action = "" method = "post" name = "school_form">
<select name="school" size ="10">
<?php
//shows options for $selected_school
$sql = "SELECT DISTINCT school FROM data;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
// inserts all data as array
echo "<option>". $row['school'] ."</option>";
}
}
?>
</select>
<br>
<input type ="submit" name = "submit_school" value = "Enter">
</form>
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
</div>
<div class ="courses">
<h3>Please select the courses you took</h3>
<form action = "" method ="post" name ="course_form">
<?php
//user shown options for courses
$sql2 = "SELECT transfer_course, transfer_title FROM data WHERE school = ? ORDER BY transfer_course ASC";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql2)) {
echo "SQL statement failed";
} else {
mysqli_stmt_bind_param($stmt, "s", $selected_school);
mysqli_stmt_execute($stmt);
$result2 = mysqli_stmt_get_result($stmt);
while($row2 = mysqli_fetch_assoc($result2)){
echo "<input type='checkbox' name ='boxes[]' value = '" . $row2['transfer_course'] . "' >" . $row2['transfer_course'] . "<br>";
}
}
?>
<br>
<input type ="submit" name = "submit_courses" value = "Enter">
</form>
<br>
<?php
//saved selected option(s) as $selected_course
if(isset($_POST['submit_courses'])){//to run PHP script on submit
if(!empty($_POST['boxes'])){
foreach($_POST['boxes'] as $selected_course){
echo "You have selected: " . $selected_course . "</br>";
}
}
}
?>
</div>
<div class = "output">
<h3>Course Equivalency</h3>
<?php
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
$result3 = mysqli_query($conn, $sql3);
if($result3)
{
while($row3 = mysqli_fetch_assoc($result3)){
echo $row3['arcadia_course'] . " " . $row3['arcadia_title'] . "<br>";
}
} else {
echo "failed";
echo $sql3;
}
?>
So by the time I get to my next sql statement
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " . $selected_school . " AND transfer_course = " . $selected_course . "";
When the school is selected, it saves the variable, but when the course is selected, $selected_school becomes blank again.
I already have session_start() at the top of the page.
You can used session variable ,it will help to make data accessible across the various pages .
So,whenever form get submitted you can save that value in session and retrieve it anytime.In top of your php file you need to start session i.e session_start(); .Then in your code
<?php
//saves selected option as $selected_school
if(isset($_POST['submit_school'])){
$_SESSION['selected_school ']=$selected_school;// here you are storing value to session
$selected_school = mysqli_real_escape_string($conn, $_POST['school']);
echo "You have selected: " .$selected_school;
}
?>
Same you can do with your $selected_course also .Then you can passed value to your query like below :
$sql3 = "SELECT arcadia_course, arcadia_title FROM data WHERE school = " .$_SESSION['selected_school ']. " AND transfer_course = " .$_SESSION['selected_course']. "";
For more information refer here
It looks like your option doesn't have a value it is passing. Try this in your first form while loop:
echo '<option value="' . $row['school'] . '">' . $row['school'] . '</option>';
It looks like there may be some more issues you are having as well. If this doesn't fix your issue, I'll dig deeper.
EDIT: Then, yes, as others have suggested, you probably want to add a hidden input field to pass that variable value on the second form submit as well.
What we are saying about the hidden input field is this:
<input type="hidden" name="selected_school" value="<?php if(isset($selected_school) echo $selected_school; ?>">

Show all tables from database into select form in php

Hiho,
I have a little problem with showing all table names on page in form .
Code bellow:
<select name="users" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
$result = mysql_list_tables($db_name);
for ($i = 0; $i < count(mysql_num_rows($result)); $i++){
echo '<option value="' . mysql_tablename($result, $i) . '">' . mysql_tablename($result, $i) . '</option>';
}
echo '</select>
</form>
<br>
<div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';
I try with mysqli too ,and i get results but still without names of the tables and nothing can be select.
Maybe someone know how to get this work.
First, you definitely want to be using MySQLi, as the MySQL extension is deprecated. Second, you can probably get all of the data you need in a simple SELECT query like this:
select `TABLE_NAME` from information_schema.tables
Try this
$mydbname = 'database_name';
$con=mysqli_connect("localhost","my_user","my_password",$mydbname);
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$options = '';
// for the query you can use two of the following lines (line1+line2 OR line3+line4)
//Use line (line1+line2)
$result = mysqli_query($con,"SHOW TABLES");
$column_name ='Tables_in_'.$mydbname;
// OR (line3+line4
$result = mysqli_query($con,"SELECT TABLE_NAME AS tbl FROM information_schema.tables" WHERE TABLE_SCHEMA = \"'.$mydbname.'\"; ");
$column_name ='tbl';
while($row = mysql_fetch_array($result))
$options .= '<option value="' . $row[$column_name] . '">' . $row[$column_name] . '</option>';
echo '<select name="users" onchange="showTables(this.value)">';
echo '<option value="0">Select a table:</option>';
echo $options;
echo '</select>';
I modify code to this:
<select name="db_tablelist" onchange="showTables(this.value)">
<option value="">Select a table:</option>';
$result = mysqli_query($con,"SHOW TABLES");
while($row = mysqli_fetch_array($result)) { echo '<option value="' . $row[0] . '">'.$row[0].''; } echo '';
echo '</select>
</form>
<br>
<div id="tablesDb"><b>All content from selected table will be listed there.</b></div></div>';
And now everything works .

PHP: select current option

I have a DB table with all categories (id, category) and table with all of events (id, event, categoryID).
And on the event editing form I have the select field with all of the categories (getting from the DB). But sinse I'm developing an editing form, I need to select current category by default.
This is my select field (PHP method that gets all the categories from DB and puts them in the following order):
<option value="1">Cat1</option>
<option value="2">Cat2</option>
<option value="3">Cat3</option>
<option value="4">Cat4</option>
<option value="5">Cat5</option>
Let's say, current event is under category 3, so I need the following HTML to be generated:
<option value="1">Cat1</option>
<option value="2">Cat2</option>
<option value="3" selected>Cat3</option>
<option value="4">Cat4</option>
<option value="5">Cat5</option>
How do I achieve it with PHP, if I have the catID?
Hopefully, this question is clear enough. Sorry for my bad explanation
UPD: This is my PHP code that generates category list:
public function getCatList($conf) {
$mysqli = $this->dbConnect($conf);
// Quering...
$query = "SELECT * FROM categories";
$result = $mysqli->query($query);
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['id'] . '">' . $row['category'] . '</option>';
}
}
Appending to your while iteration a condition will solve this for you:
while($row = mysqli_fetch_array($result)) {
$isSelected = $row['id'] == $catID;
echo '<option '.($isSelected ? 'selected="selected"' : '').' value="' . $row['id'] . '">' . $row['category'] . '</option>';
}
You're making a comparison if the current value is the same as that stored in $catID - and store the boolean result in a variable. In the echo you're just doing a conditional forking and appending the selected attribute if the value was true, otherwise not appending any empty string.
You can do it like
while($row = mysqli_fetch_array($result)) {3
echo '<option value="' . $row['id'] . '"';
//if condition is met then make the option selected
if($row['categoryID'] == 3) {
echo " selected='selected' ";
}
echo '>' . $row['category'] . '</option>';
}
you should add the selected catID as a parameter to your getCatList-function. Then just change the creation of your HTML to include the selected-attribute:
public function getCatList($conf, $catID = 0) {
$mysqli = $this->dbConnect($conf);
// Quering...
$query = "SELECT * FROM categories";
$result = $mysqli->query($query);
while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row['id'] . '"' . ($row['id']==$catID?' selected':'') . '>' . $row['category'] . '</option>';
}
}
now you can just pass the catID to your function:
$myConf = "something";
$myCatID = 3;
getCatList($myConf, $myCatID);
//query for the categories and options
$current_value = 3;
$total_num_of_options = mysql_num_rows($your_query_result);
for($count = 1; $count <= $total_num_of_options){
echo "<option value='".$count."' ";
if($count == $current_value)
echo "selected";
echo ">cat".$count."</option>";
}

Variable not being passed to second select dropdown

I have two dropdowns, one displays States from HTML SELECT, and the next one populates from MYSQL query of markets matched to the state selected. After selection of the Market, the SID should appear. The problem is the code remembering the $pickstate var when you select the $market var so Mysql query can display the SID result.
<?php
// Get State from above form.
$pickstate = $_POST['state'];
$result = mysql_query("SELECT Market FROM ppc WHERE State='" . $pickstate . "'");
// After State is selected from MySQL, populate Market Dropdown.
echo '<form style="display:inline-block;" action="" method="POST"><select id="Market" name="Market" onchange="this.form.submit();">';
echo '<option value="">Select Your Market</option>';
while ($row = mysql_fetch_array($result)) {
echo ( '<option value= "' .$row['Market']. '">'.$row['Market'].'</option>' );
}
echo "</select></form><br />";
// Get SID Result
$market = $_POST['Market'];
$sid = mysql_query("SELECT SID FROM ppc WHERE State='" . $pickstate . "' AND Market='" . $market . "'");
// This is for debugging only.
// This shows, until market is selected.. then vanishes.
echo $pickstate . "<br />";
// This shows after market has been chosen.
echo $market . "<br />";
// "SHOULD" Display SID.
if ($state != null && $market != null) {
echo '<p style="display:inline-block;margin:0;padding:0;"> Use: ';
}
while ($row = mysql_fetch_array($sid)) {
echo $row['SID'] . ' ';
}
?>
it will not work like that .
the query is server side . you may consider to send your selected value to another page and then get values from your query
OR you can use ajax .

dynamic dropdown filled from mysql data

What i'm trying to do is display a drop down with all field names from mysql database, once the user picks one and submits the form i want to display a second dropdown filled with all the rows from the submitted field name, this is my code so far:
$result = mysql_query("select * from `parts`") or die(mysql_error());
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
echo "<select name='field_names'>";
$i = 0;
while ($i < mysql_num_fields($result)) {
$fieldname = mysql_field_name($result, $i);
echo '<option value="'.$fieldname.'">'.$fieldname.'</option>';
$i++;
}
echo "</select>";
echo "<input type='submit' value='submit'></input>";
echo "</form>";
if($_POST) {
$fields = $_POST['field_names'];
$result1 = mysql_query("select '".$fields."' from `parts`") or die(mysql_error());
echo '<select name="fields">';
while ($row = mysql_fetch_array($result1)) {
echo "<option value=".$row[$fields].">".$row[$fields]."</option>";
}
echo '</select>';
}
Can anyone spot where i'm going wrong, thanks
there is a mistake on the line number 29
$result1 = mysql_query("select '" . $fields . "' from `parts`") or die(mysql_error());
you are using ' instead of `. Do as follows
$result1 = mysql_query("select `" . $fields . "` from `parts`") or die(mysql_error());
Hope your problem is solved.
As it stands now, the second set of selects will be issued OUTSIDE of your </form> tag, so will never get submitted with the rest of the form. At best, you should move the form closing tag to below the POST handler.
here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";}
echo "</select>";
here username is the column of my table(userregistration)
it works perfectly

Categories