I am dumping some results from the database directly into tag in the html, how I can make the first option value to be null, and after that the database results to be sorted? This way I will have this drop down menu an option to not choose anything from it.
this is my code here:
<?php
$select = new Users;
$stmt = $select->selecttema();
while( $row = $stmt->fetch()){
echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
}
?>
Just
echo '<option value="">Select a topic</option>'
before the while loop.
actually Juan Pablo had answered the question. i just add something on his answer.
if you add selected in your option it will be first option and you do not need to add data in value
echo '<option selected value="">Select a topic</option>';
To make an empty option:
<select>
<option value="">Select</option>
<?php
$select = new Users;
$stmt = $select->selecttema();
while( $row = $stmt->fetch()){
echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
}
?>
</option>
You're not clear about what this Users object is or how you're fetching data so I'll just assume you're using a mySQL database, in which case you can use ORDER BY:
SELECT * FROM `users` WHERE 1 ORDER BY id DESC
For instance the above statement will select all users in the users database and order them by their id in descending order.
To sort the <select> options in JS, take a look at Sort Select Options by Value Attribute Using jQuery and Javascript to sort contents of select element
Related
I'm programming a simple form with a dynamic dependent selection. There are two files. One is a php file with html, javascript and php inside, the second is a php file to get data for the second selection and send them back in json format. In the first (and main) file I have the form with two select fields. First field is for province, second is for towns. Data are in a MySQL db, two tables, table_provinces for provinces (103 rows) and table_towns for towns (8000 rows). Normally connect to the db as usual and also link to jquery using a javascript link. First I get provinces options for the first select field, using php to get the values from table_provinces of the db. Then with the javascript " on('change',function(){ here I use ajax...}) " I pass the selected value using ajax to a php file that might extract towns from table_towns and give back (in json format) values to populate the second select field. Javascript gets correctly the selected value from the first selection field (I used an alert to know it), but nothing more happens. So this is the code.
Link to jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
HTML first select field:
<form method="post" action="usemychoice.php">
<select id="province" name="province" color="white">
<option value="" selected>Select a province</option>
This is how I populate the first select field:
<?php
$sql = "SELECT * FROM table_provinces";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='".$row['prov']."'>".$row['extended_province']."</option>";
}
} else {
echo "Error: ..........";
}
?>
And after closing that field with a /select I have this code to get values for populating with town names the second select field:
<script type="text/javascript">
$(document).ready(function(){
$('#province').on('change',function(){
var provinceID = $(this).val();
if(provinceID){
window.alert("ok you've chosen the province "+provinceID);
$.ajax({
type:'POST',
url:'get_towns.php',
data: 'prov='+provinceID,
success:function(html){
$('#town').html(html);
}
});
}else{
$('#town').html('<option value="">Please select the province first</option>');
}
});
});
</script>
This is the get_town.php code:
<?php
//*****after a require to the connection db routine"
if(!empty($_POST["prov"])) {
$sql = "SELECT * FROM table_towns WHERE prov LIKE '%" .$_POST['prov']."%'";
$result = mysqli_query($conn, $sql);
$json = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
} else {
echo "Error: .................";
}
echo json_encode($json);
}
?>
Finally I have the html code :
<select id="town" name="town" color="white">
<option value="" selected>Select province first</option>
At the end of the day, the code has something wrong because I don't get any data back from get_town.php to populate the second select field, and since I didn't see a window.alert that I've put there to check ongoing execution (you don't see it in the code posted here), it seems that is not executed. Any help?
url:'get_towns.php',
Isn't it get_town.php without plural ?
Apparently it seems that the output of get_town.php is JSON
echo json_encode($json);
but in your JS it is directly output to an html element
$('#town').html(html);
Solution:
Either modify get_town.php to send html OR modify the success function in JS to convert received JSON to proper html.
I hope this will help.
UPDATE:
Replace this part of php
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
}
with something
echo '<option value="" selected>Select Town</option>';
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['town'].'" color="white">'.$row['town'].'</option>';
}
and finally remove the line
echo json_encode($json);
I have a form where user selects the category while adding the product.
When user want to edit the product, i am displaying all the previously populated values but could not able to figure out how to display the category he selected.
addproduct.php (displaying the categories from the database)- this code is working fine and can see all the categories in dropdown
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
In the edit product i want to display all the categories like above, but want to display the selected category in the form which i could not able to do.
editproduct.php (rough draft code) -- not working
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option select="<?php echo $cat;?>"value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
$cat - category value(previously selected) pulled from database
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
<option value="<?php echo $cat;?>"><?php echo $cat;?></option>
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<?php if($cat!=$subjectData['name']){?> <option value="<?
php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
<?php } ?>
Try using this code and please use mysqli as mysql is deprecated. previously selected category should be before while loop. Hope it helps
Two issues with your code:
You are using mysql functions, which are depreciated and don't even exist in the current version of PHP. Use mysqli or PDO functions.
The html you are generating is invalid syntax.
I'll leave the first issue to you to correct.
For the 2nd issue, all of the non-selected options in your dropdown will not have the selected attribute.
Only the selected item will have that attribute. The code below assumes that the variable $cat has the previously selected value, and each row has a
column named 'cat'. When $cat matches the value in the column 'cat', it will add selected='selected' to the option.
<?php
require 'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];
$selected = "";
if($cat == $subjectData['cat']) {
$selected = "selected='selected' ";
}
echo "<option ".$selected."value=".$subjectData['name'].">";
echo $subjectData['name'];
echo "</option>\n";
}
?>
I'm trying to make an invoice php page which contain 2 dropdown option: Supplier_Name and Item_ID. Both of them is not predetermined. Supplier_Name option obtained from another page (List of Supplier, which can be modify). Item_ID option obtained from another page too (List of Item, which can be modify too). I'm quite new about this and my data is small, so I'm looking the simplest way possible.
So far, I knew how to populate Supplier_Name from List of Supplier database. I used this code:
<td>Supplier</td>
<td>
<?php
mysql_connect("localhost","root","");
mysql_select_db("stock");
$result = mysql_query("SELECT * from input_supplier_data");
$jsArray = "var invoice = new Array();\n";
echo '<select name="supplier_name" onchange="changeValue(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['supplier_name'] . '">' . $row['supplier_name'] . '</option>';
$jsArray .= "invoice['" . $row['supplier'] . "'] = {name:'" . addslashes($row['supplier']) . "',desc:'".addslashes($row[''])."'};\n";
}
echo '</select>';
?>
</td>
<br /<input type="text" name="input_supplier_data" id="input_supplier_data"/>
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(id){
document.getElementById('input_supplier_data').value = supplier_name[id].name;
};
</script>
When a Supplier selected, only their product will be displayed in the second dropdown option. Since List of Item page contain all item from all supplier, I don't know how to limit them. What I can do so far is only if the supplier was predetermined. I used this code:
SELECT input_item_data.`item_id` FROM `input_item_data` WHERE input_item_data.`supplier` = 'UNILEVER'
But as I stated earlier, the item is not predetermined, it can be modify in List of Item page. Hope anyone can help me. Thanks.
I have two dropdowns in my form.
1)Brand Name of car
2)Model name in which data is going to be retrieved from database on the basis of brand name selected.
so I have taken a div tag and appended that second dropdown.The data in dropdown is displayed properly but the problem is in storing the data selected from the second dropdown, It stores the model name upto the space only.length in the database for that field is also taken properly.
eg- if the model name is "series 1" than it will store only series.
Php page of second dropdown:
<?php
$brand = $_GET['brand'];
include('connection.php');
$sql = "select * from modelname where Brand_Name='" . $brand . "'";
$result = mysqli_query($conn, $sql);
$html = "";
$html = '<select name="model">';
while ($row = mysqli_fetch_assoc($result)) {
$html.='<option value=' . $row['M_Name'] . '>' . $row['M_Name'] . '</option>';
}
$html.='</select>';
echo $html;
?>
because you are not quoting your attributes.
value=hello world
is seen as
value="hello" world
Add the missing quotes.
I don't know much about Javascript and Jquery, but I do have to use it on a HTML select tags. I have two database tables, grouptypes and groups. A grouptype can have multiple groups, but a group only belongs to one grouptype. I have two select tags, one is grouptypes and another one is groups. What I want to do is that whenever a user select a grouptype in the grouptypes dropdown menu, it triggers a handler to retrieve the corresponding groups that belong to that grouptype. I need javascript or Jquery to get it done, but I am not able to write it myself. So anyone can help me? I would so appreciate it.
GroupType: <select name="groupType">
<?php foreach($grouptypes as $type) : ?>
<?php echo "<option value='" . $type['name'] . "'>" .$type['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
Group: <select name="groups">
<?php foreach($groups as $group) : ?>
<?php echo "<option value='" . $group['name'] . "'>" .$group['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
<?php
$query = "SELECT id, name FROM group_type";
$grouptypes = $_db->getResultsForquery($query);
$query = "SELECT id, name FROM groups";
$groups = $_db->getResultsForquery($query);
?>
Here's what I would do. It uses jquery to send a get to a page called groups.php which will return some html you can parse. Then you parse it :)
$('#grouptype-select').change(function(){ //.change will detect when the select has been changed (an -option- has been chosen)
var grouptype = $(this).val(); //create a variable from the -option- chosen
$.get('groups.php', 'grouptype=' + grouptype, function(response){ //use jquery to send -get- to groups.php
$('#list-of-groups').html(response); //insert response into ur doc
}
});
Something like http://www.yoursite.com?grouptype=abc will be sent using get asynchronously (ajax) Good luck!
PS Here is a jsfiddle to get you tinkering: http://jsfiddle.net/yLyTw/1/