I have a drop down menu having column names same as they are in database table. I have inserted every column name in option tag of dropdown menu. These columns have number of rows in database.
After that, I have another drop down menu. I want to show all the data rows of the selected column in the previous drop down menu.
E.g. I have column names as a,b,c,d in the first drop down and every column has data in database table. So, If I select A in first drop down; It shows all the data rows of A in next drop down. Here is the code:
<select name="first">
<option selected="true" disabled="disabled">Select an Option</option>
<option value="select_all">Select All</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">c</option>
</select>
<?php
if(isset($_POST['first'])){
$first=$_POST['first'];
}
?>
<select name="firstres" id="firstres"><option style="display:none;" selected; value="">---Select an option---</option><?php
#mysql_connect('localhost', 'root', '');
#mysql_select_db('db');
$first=$_POST['first'];
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'db' AND TABLE_NAME = 'tbl' AND COLUMN_NAME LIKE '" . $_POST["first"] . "'";
$result = #mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value=' " . $row['first'] ."'>" . $row['first'] ."</option>";
}
?>
</select>
The problem is; I am not getting column rows in second drop down menu.
You need to use Ajax for this issue, here my code maybe you can use on your projects.
View Code
<select id="category">
<option value="1">Category</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
<select id="sub_category">
<option>Chose Category</option>
</select>
Ajax Code
$(document).ready(function(){
$('#category').on('change',function(){
var category_id = $(this).val();
if(category_id){
$.ajax({
type:'POST',
url:'sub_category.php',
data: {
category_id : category_id
},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option>Pilih Sub category Kelas</option>');
}
});
});
sub_category.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category_id = $_POST['category_id'];
$sql = "SELECT id,sub_category FROM category where category_id = $category_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row["id"]."'>".$row["sub_category"]."</option>";
}
} else {
echo "<option>Empty Sub Category</option>";
}
$conn->close();
?>
First of all, I do recommend to stay in php for the whole code.
-> Make things easier for the future...
Example:
$output = <<< EOD
<option>Select an Option</option>
etc.
EOD;
echo $output;
Second, did you run through the code step by step?
what is the output for $first and $_POST['first']; ?
Are they correct?
Is the SQL statement correct?
Table and column names....
Third, I understand, that you want select from the first dropdown and than the output from the database should appear.
This won't work in that way. HTML is stateless. This means everything which has been send to client is no longer available for the server.
So you need to use some code to resend this information: For example JSON (AJAX) or via HTML (which is not so nice). Look here:
https://www.w3schools.com/js/js_ajax_intro.asp
Related
I'm building a system that tracks contact lenses. I'm storing the contact lens info in a database as sometimes prices/availabilities change and i access this info from multiple points in the program. I'm trying to interface with this list using a dropdown by doing "SELECT * FROM contacts" as a query. my code looks like this :
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
Then I echo that list out in a while loop using PHP to populate the options in the dropdown.
My question is this: I have these dropdowns for each eye on the same form. So it's "Brand Right Eye"....other miscellaneous info about the right eye....then "Brand Left Eye". But ONLY the right eye is populating with the brand info because it appears first in the code. What i'm having to do is copy/paste the exact same query and do
$contact_list2 = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
then later if I need the dropdown again, I need to do $contact_list3..and so on. Why can i not generate a drop down using the same variable? Why does it stop responding to calling the variable after the first execution of it and is there any work around that I can implement that would allow me to not have to copy/paste the same query with a different variable association each time?
just for refernce, my php while code is this:
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
while($row = mysqli_fetch_array($contact_list))
{
?>
<option value = "<?php echo($row['brand'])?>" name = "brandOS">
<?php echo($row['brand']) ?>
</option>
<?php
}
?>
</select>
I have this loop copy/pasted for right eye and left eye. But it only works on which ever drop down appears first in the code.
A possible solution will be more efficient in term of performance could be :
<?php
$left_eye = '<option value="0">Please Select</option>';
$rigth_eye = '<option value="0">Please Select</option>';
while($row = mysqli_fetch_array($contact_list))
{
//logic for left eye
$left_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
//logic for rigth eye
$rigth_eye .= <<<HTML
<option value ="{$row['brand']}" name = "brandOS">
{$row['brand']}
</option>
HTML;
}
?>
<select class="form-control" name = "brandOS">
<?php echo $left_eye ; ?>
</select>
<select class="form-control" name = "brandOS">
<?php echo $rigth_eye ; ?>
</select>
With this solution you get your result in the same while loop. If the left and right select are the same you can use the same variable.
Store the brands in an array, then you can just loop through the array.
<?php
$contact_list = mysqli_query($link, "SELECT brand FROM contacts ORDER BY brand");
$brands = array();
while($row = mysqli_fetch_array($contact_list))
{
array_push($brands, $row['brand']);
}
?>
<select class="form-control" name = "brandOS">
<option value="0">Please Select</option>
<?php
foreach($brands as $brand){
?>
<option value = "<?php echo($brand[0])?>" name = "brandOS">
<?php echo($brand[0]) ?>
</option>
<?php
}
?>
</select>
You can use a PHP array, like the SESSION one, to store values and use them across your site. Be sure you call "session_start()" method on each page you use that array, though.
//Initialize sessions
session_start();
...
//Right after getting result from query
$_SESSION['contact_list'] = $contact_list;
To use it, just be sure to call the method I told you above, and call the variable with the same syntax:
<?php
while($row = mysqli_fetch_array($_SESSION['contact_list'])) { ?>
Hope this helps.
I have a drop down list which i filled with items from my database "mydatabase".
connect.php
<?php
$dbname = 'mydatabase';
$dbuser = 'louie';
$dbpass = '';
?>
mydatabase contains the table 'Users' with 'Name' and 'NameID' column.
index.php
<?php
include ("connect.php");
$mysqli = new mysqli("localhost", $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<div class="label">Select Name:</div>
<select name="names" onchange="change(this.value)">
<option value = "none">---Select---</option>
<?php
$query = "SELECT `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='{".$d['Name']."}'>".$d['Name']."</option>";
}
?>
</select>
<select name="nid" id="nameid">
</select>
In my name column there is two values. Louie and Jane which fills the first dropdown "names". What I want to do is whenever I select the Louie, the second drop down with the id 'nameid' will be filled with the NameID column from my database.
I've got some idea in disabling the second drop down but without the database.
<script>
function change(value) {
if(value=="none")
document.getElementById("nameid").disabled=true;
else
document.getElementById("nameid").disabled=false;
}
</script>
But I don't know how to fill the second dropdown with NameID column by selecting the Louie in first drop down.
try something like this:
var x = document.createElement("OPTION");
x.text = value;
var s = document.getElementById("nameid");
s.add(x);
The trick here is to understand that only PHP can access your database, and that reacting on UI changes is a javascript issue. That means that if you want the nameID on your second dropdown, php first needs to already provide it somewhere, and next you'll need some javascript to actually show it.
This is a possible solution:
<!-- note I changed the function onchange="change(this.value)" to onchange="change(this)"
because this.value is actually not the value.. -->
<select name="names" onchange="change(this)">
<option value = "none">---Select---</option>
<?php
// Select both columns you want to use in PHP
$query = "SELECT `NameID`, `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
// I used the value field to hold the id, rather than the name, while the name is shown to the user.
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='".$d['NameID']."'>".$d['Name']."</option>";
}
// your other code...
?>
<script>
function change(oSelect) {
var value = oSelect.options[oSelect.selectedIndex].value;
var name = oSelect.options[oSelect.selectedIndex].innerHTML;
if(name=="Louie") {
document.getElementById('nameid').innerHTML = "";
for (var i=0; i<oSelect.options; i++) {
document.getElementById('nameid').innerHTML += "<option value='"+oSelect.options[i].value+"'>"+oSelect.options[i].value+"</option>";
}
}
}
</script>
I'm trying to populate an html table from my SQL query based on a user's selections. I'm able to populate the first column however, my variable column "select_datapoint" is blank. Is there any reason this won't work?
<form>
<select name="select_datapoint">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
<option value="test5">test5</option>
</select>
<select name="minput">
<option value="ME">ME</option>
<option value="CT">CT</option>
<option value="AZ">AZ</option>
<option value="DE">DE</option>
<option value="MT">MT</option>
</select>
<input type="submit" name="Submit">
</form>
<br></br>
<?php
print date("g:i a.", time());
?>
<br></br>
<!--use PHP to connect to sql database-->
<?php
$servername = "sql206.phpnet.us";
$username = "pn_14163829";
$password = "714405c";
$dbname = "pn_14163829_mexico";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$zurich = $_GET["minput"];
$montreal = $_GET["select_datapoint"];
$sql = "SELECT test1,'$montreal' AS testX FROM test WHERE test1='$zurich'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<table class=\"v\">";
echo "<th>test1</th><th>$montreal</th>";
while($row = $result->fetch_assoc()) {
echo "<tr>"."<td>".$row["test1"]."</td>"."<td>".$row['testX']."</td>"."</tr>";
}
} else {
echo "0 results";
echo "<br></br></table>";
}
$conn->close();
?>
$sql = "SELECT test1,'$montreal' AS testX FROM test WHERE test1='$zurich'";
Mark's answer is correct, but not for the reason he gives.
He says that the above will treat '$montreal' as a string literal. Normally that is correct, but because it's embedded in a double quoted string, it will actually be interpolated correctly.
What's actually happening is that you're generating a string along the lines of:
SELECT test1,'fieldname' AS testX FROM test WHERE test1='$zurich'
The 'fieldname' is incorrect - it's a column name. Single quotes in an SQL query are for values, so MySQL isn't interpreting this as you expect. If you want to use quotes for a column (or table) name, you need to use backticks:
$sql = "SELECT test1,`$montreal` AS testX FROM test WHERE test1='$zurich'";
Will work. Though as you noticed, you can get the same effect by omitting any quotes.
This is invalid PHP Code:
'$montreal'
Single quotes will not process variables inside of them. Change it to double quotes:
$row["$montreal"]
Or, better yet, remove the quotes all together:
$row[$montreal]
Read more here:
What is the difference between single-quoted and double-quoted strings in PHP?
I want to create a php page that contains a html drop down list of people's names (as the option
text) and then their age (as the value). Below is my form for you to see (almost what I mean) which I hard coded:
<form>
<select name="nameOption">
<option value="">Select your name:</option>
<option value="45">Mary Smith</option>
<option value="16">Lily Roe</option>
<option value="32">Elliot Perkins</option>
</select>
<p><input type="submit" name="submit" value="Submit"/>
<input type="reset" value="Reset" />
</form>
What I want to do (or been trying to do) is to create the drop down list by running a SQL query to obtain the data (the people's name and age) from my database (unlike what I written above) and then when I click on one of the options, only their value or age should appear. So basically, I need to implement the data from the database into a drop down list
Now it's here where I am stuck. I am familiar with writing SQL statements for tables but I seem to get puzzled when I try to create a SQL statement for a drop down list in a php tag.
How would I write it? Like:
$sql = "SELECT name, age FROM person WHERE name = ". $person. ";
or
$nameOption = $_POST['nameOption'];
print_r ($nameOption);
with selecting a database:
$conn = mysql_connect("localhost", " ", " ");
mysql_select_db(" ", $conn)
I know it may seem like a dull answer but I need help. How would I implement SQL query to a drop down list? I would love your help.
As you have to enclose string in quotes, change your query to
$sql = "SELECT name, age FROM person WHERE name = '$person'";
and for showing dropdown dynamically you can do like
$query=mysql_query($sql);
echo '<select name="nameOption">
<option value="">Select your name:</option>';
while($result=mysql_fetch_array($query))
{
echo '<option value="'.$result['age'].'">'.$result['name'].'</option>';
}
echo '</select>';
You should do like that
<select name="nameOption">
<?php
$query = mysql_query($sql);
while( $row = mysql_fetch_array($query) ) {
echo '<option value="'.$row['age'].'">"'.$row['name'].'"</option>';
}
?>
</select>
You need to get the full list of people from the database first, then iterate through that outputting each option tag for each row:
$cnx = new Mysqli('localhost', 'username', 'password', 'database_name');
$people = $cnx->query("SELECT name, age FROM person");
echo '<select name="nameOption">';
while($person = $people->fetch_assoc())
{
echo '<option value="' . $person['age'] . '">' . $person['name'] . '</option>';
}
echo '</select>';
I have a drop down menu with two options in html, I also created a PHP script that checks what option from the drop down menu has been selected and based on the selection executes a mysql query to fetch data from database.
But I am also trying to echo out a new drop down menu with the results obtained from database and that is where the I am struggling because no errors are diaplayed but also no drop down menu is 'echoed' out onto the page.
HTML:
<?php require "course.php" ?>
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP code:
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value=''>".$result2['course']."</option>";
}
echo "</select>";
echo '</br>';
}
Could someone point out a mistake I am doing or perhaps suggest where I could look for answers
you said $query2 is displaying value in print_r.so the only mistake i find in your code is display:none .
remove display:none
echo "<select id='Forex' name='Forex' style='display: none'>";
----------------------------------------------------------------------^