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";
}
?>
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'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 am showing the dropdowns based on the above selected dropdowns. I want the result in third dropdown. For that I am writing the sql query in php and writing the change event in jquery but i am unable to get the result. I am stuck up there
My jquery looks like
$(document).ready(function(){
$("#parent_cat,#city").change(function(){
$.get('loadlocation.php?city=' + $(this).val() , function(data) {
$("#sub_cat").html(data);
});
});
});
parent_cat and city are from selected values
<label for="category">Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label for="city">city</label>
<select name="city" id="city">
<?php while($row = mysql_fetch_array($query_parent1)): ?>
<option value="<?php echo $row['city']; ?>"><?php echo $row['city']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
And my php file loadlocation.php is
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$city = $_GET['city'];
$query = mysql_query("SELECT table_place_detail.post_title FROM table_terms, table_place_detail, table_post_locations
WHERE table_place_detail.post_location_id = table_post_locations.location_id AND table_place_detail.default_category = table_terms.term_id AND table_post_locations.city = '$city' AND table_terms.name = '$parent_cat'");
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[post_title]'>$row[post_title]</option>";
}
?>
I want to fetch the values of parent_cat, city to loadlocation.php but i am not able to get those values. I want to load the two values and get the query excecuted and the values should shown in 3rd dropdown as below can any one help this issue
<label>Vendors List 1</label>
<select name="sub_cat" id="sub_cat"></select>
Two things stand out
You send only one value, ?city=
According to the manual jQuery.get(), you can send additional parameters as a plain object. This means, you don't need to build a query string, but can pass parent_cat and city separately, e.g.
$.get("loadlocation.php",
{ parent_cat: $('#parent_cat').val(), city: $('#city').val() },
function(data) {
$('#sub_cat').html(data);
});
And finally, the mandatory hint at each mysql_* page
Warning This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
in my code i'm showing drop down select field list base on user school choice. for example -
if user choose 'School of Economics' from drop down list, i'm showing in another drop down list just the relevant lanes (based on a mysql query).
to do this i have 5 div's, on for etch school:
<div id='a'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 1 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
<div id='b'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 2 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
i have a listener to show just the right 'lane' div when user chooses school and hide all other 'lane' div's:
$(document).bind('pageinit', '#indexPage', function(){
$("#a").show();
$("#b").hide();
$("#c").hide();
$("#d").hide();
$("#e").hide();
//this will call our toggleFields function every time the selection value of School field changes
$("#school").change(function () {
toggleFieldsA();
toggleFieldsB();
toggleFieldsC();
toggleFieldsD();
toggleFieldsE();
});
});
function toggleFieldsA() {
if ($("#school").val() == 'School of Economics'){
$("#a").show();
}
else
$("#a").hide();
}
function toggleFieldsB() {
if ($("#school").val() == 'School of Computer Science')
$("#b").show();
else
$("#b").hide();
}
the problem: when user submit the form, i get the wrong 'lane_name' from POST array. i'm getting the last school selected lane value (that is hidden from the user) and not the user selected lane name , plz help
You need to give each <select> element a unique name, otherwise the last element with a particular name will be the only one you can access. PHP has no way of determining which of the 5 lane_name you are referring to.
To figure out what option set was selected you could make the first option blank: <option value=""></option>. You can add some logic to reset to the blank option when you hide/show the DIVs so only one of the lane_names will have any data in it.
The mysql_* is depreciated as of PHP 5.5.0. You should consider switching to mysqli.
I am working on a very basic administrator functionality of a social network and I came across this issue of not being able to remove an option from select dropdown list that I previously generated using jquery. The dropdown list contains all users of the social network. Administrator upon clicking on "Delete account" deletes the corresponding record from the database.
Now the question being - when I click on "delete account" it works perfectly fine but the option with a username is still there in a dropdown list and is possible to be picked - when picked it obviously returns dozens of PHP warnings and errors because the record is not in a database anymore. How can I remove this option straight away? I tried something like the following, but it doesn't work.
admin_panel.php (only relevant stuff)
<select name='users' id='users'>
<option value="" disabled selected>Select user</option>
<?php
$sql = mysql_query("SELECT * FROM users WHERE id <>'".$_SESSION['user_id']."'ORDER BY username DESC") or die(mysql_error());
$userList = [];
while($row=mysql_fetch_assoc($sql)){
$username = $row['username'];
$userID = $row['id'];
$userList .= '<option name="userID" value='.$userID.'>'.$username.'</option>';
}
echo $userList;
?>
</select></br></br></div>
<div id="user_info">
<!-- generated user info table-->
</div>
<script type="text/javascript">
"$('#user_info').on('click', '#deleteAccount', function(e){
data.command = 'deleteAccount'
data.userID = $('#users').val()
$.post(theURL, data, function(result){
//Do what you want with the response.
$('#delete_account_success').html(result);
})
$("#users option[value='data.userID']").remove();
$('#delete_account_success').show();
$('#delete_account_success').fadeOut(5000);
})
</script>
processUser.php (part of a switch statement)
if(isset($_POST['command'])){
$cmd = $_POST['command'];
$userID = $_POST['userID'];
$sql=mysql_query("SELECT * FROM users WHERE id='".$userID."'");
$userData = [];
while($row = mysql_fetch_assoc($sql)){
$userData['userid'] = $row['id'];
$userData['username'] = $row['username'];
$userData['name'] = $row['name'];
$userData['date'] = $row['date'];
$userData['email'] = $row['email'];
$userData['avatar'] = $row['avatar'];
$userData['about'] = $row['about'];
$userData['admin'] = $row['admin'];
}
switch($cmd){
case 'deleteAccount':
$sql= "DELETE FROM users WHERE id =".$userID;
$result=mysql_query($sql);
echo "<img src='pics/ok.png' class='admin_updated_ok'>";
break;
}
On this line
$("#users option[value='data.userID']").remove();
You're removing any option items from #users where the value is equal to the string literal data.userID
Try changing it to
$("#users option[value='" + data.userID + "']").remove();