I'm having a hard time figuring this out.
This is my html with drop down list, it's working as it should. But the thing is, I don't have a clue on how to output the Stock data that's in Stock Column of itemprofile table in a way that every time I pick a different product on the drop down list, Stock value should also change accordingly.
<html>
<body>
<form>
<select name="product" />
<?php
$mysqli = new mysqli("localhost", "root", "","bsystem");
$results = $mysqli->query("SELECT * FROM itemprofile");
if ($results) {
while($obj = $results->fetch_object())
{
echo '<option value="'.$obj->productname.'">'.$obj->productname.'</option>';
}
}
?>
</select>
Available Stock: <?php NO CLUE WHAT TO DO HERE?>
</form>
</body>
</html>
The content of my database:
3 columns: id, productname, stock
1 item1 50
2 item2 30
3 item3 10
Hope you guys can help me out figuring this out. Thanks!
Edit: my code so far.
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<select id="selectItem">
<option>-- Select item --</option>
<?php
$mysqli = new mysqli("localhost", "root", "","bsystem");
$results = $mysqli->query("SELECT * FROM itemprofile");
$itemsStock = array(); # create an array where you will keep your stock values for each item
if ($results) {
while($obj = $results->fetch_object()){
echo '<option value="'.$obj->productname.'">'.$obj->productname.'</option>';
$itemsStock[$obj->id] = $obj->stock; # fill array with stock values
}
}
?>
</select>
Available stock: <div id="stockValue"></div>
<script>
var stockValues = <?php echo json_encode($itemsStock);?>; // transfer array that contains item stock values from php to the javascript array
$("#selectItem").change(function(){ // on every DropDown change
var ItemID = $(this).val(); // get selected item id
console.log(ItemID);
var ItemStockValue = stockValues[ItemID]; // search stock value in your array of stock values by using ItemID
$("#stockValue").html(ItemStockValue); // update Available stock for selected item
});
</script>
</body>
</html>
You can do it by using jQuery. You have comments in the code so that you can understand the logic of this solution. By this you can also update multiple values on dropdown change. Code may have some syntax errors but this may solve your problem with outputing data on dropdown change.
<select id="selectItem">
<option>-- Select item --</option>
<?php
$mysqli = new mysqli("localhost", "root", "","bsystem");
$results = $mysqli->query("SELECT * FROM itemprofile");
$itemsStock = array(); # create an array where you will keep your stock values for each item
if ($results) {
while($obj = $results->fetch_object()){
echo '<option value="'.$obj->id.'">'.$obj->productname.'</option>'; // THIS LINE CAUSED THE PROBLEM, i echoed productname in value attribute, instead of id
$itemsStock[$obj->id] = $obj->stock; # fill array with stock values
}
}
?>
</select>
Available stock: <div id="stockValue"></div>
<script>
var stockValues = <?php echo json_encode($itemsStock);?>; // transfer array that contains item stock values from php to the javascript array
$("#selectItem").change(function(){ // on every DropDown change
var ItemID = $(this).val(); // get selected item id
var ItemStockValue = stockValues[ItemID]; // search stock value in your array of stock values by using ItemID
$("#stockValue").html(ItemStockValue); // update Available stock for selected item
});
</script>
Remember to include jQuery. Hope it will help you :)
Related
I'm pulling data from an Azure SQL database using PHP and have successfully created a drop-down (Select) box with Options that are pulled from the database.
The SQL query returns 2 columns, Title & Cycle_ID.
I have set the Title as the text string and the Cycle_ID as the value.
I now want to store the value (Cycle_ID) of the current selection in a variable (MyVariable), which I will use in the SQL query for the next drop-down box I'm creating, i.e. WHERE Cycle_ID = MyVariable.
This way the user progressively narrows their selection as they work their way down through my drop-down boxes.
My current code is below, but I don't know how to create and store the current selection to MyVariable.
<?php
//create the database connection and define the query
$serverName = "myserver";
$connectionOptions = array(
"Database" => "mydatabase",
"Uid" => "mysqlaccount",
"PWD" => "mypassword"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//defines cycle query
$cyclesql= "SELECT [Cycle_ID]
,[Title]
FROM [ods].[Cycle]
WHERE End_Date > DATEADD(month,-6,GETDATE()) AND Updated IS NOT NULL
ORDER BY Cycle_ID Asc";
$cycleResults= sqlsrv_query($conn, $cyclesql);
if ($cycleResults == FALSE)
echo (sqlsrv_errors());
?>
<html>
<body>
<form action="cyclefile.php" method="post">
<div id="select">
<p>Select the week:</p><select name='Week'>
<option value="">Select...</option>
<?php
//starts loop
while ($row = sqlsrv_fetch_array($cycleResults, SQLSRV_FETCH_BOTH)) {
//defines cycle variable
$cycle = $row['Title'];
//defines cycle_id variable
$cycle_id = $row['Cycle_ID'];
//displays cycle variable as option in select (dropdown) list and cycle_id as value
echo '<option value="'.$cycle_id.'">'.$cycle.'</option>';
}
?>
</select>
</div>
</form>
</body>
</html>
I suggest you to make an ajax call on selection and pass the selected value to process your result in another file where you can run your query.
<select name="cycle_data" id="cycle_id">
<option value="cycle1" > Cycle 1</option>
<option value="cycle2" >Cycle 2</option>
</select>
Then lets do a script:
<script type="text/javascript">
$(document).ready(function(){
$("#cycle_id").change(function(){
var cycle_data = $(this).val();
var dataString = "cycle_data="+cycle_data;
$.ajax({
type: "POST",
url: "get-data.php",
data: dataString,
success: function(result){
// Process your result here
}
});
});
});
</script>
So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>
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 have a database containing a name and a status column. It contains data displayed in a table (obvious!). So, I want users to be able to select the status column's data and change it to any value listed in the drop down list. After the selection, they need to click a button that will update the selected row to the mySQL database.
How can I achieve this with PHP scripting and HTML?
Here is my code for displaying the data in a table on the website: (Pay no attention to phpReportGenerator.php- its only drawing the columns as per sql table)
<?php
include_once('includes/phpReportGenerator.php');
$prg = new phpReportGenerator();
$prg->width = "100%";
$prg->cellpad = "10";
$prg->cellspace = "0.5";
$prg->border = "1";
$prg->header_color = "#307D7E";
$prg->header_textcolor="#FFFFFF";
$prg->body_alignment = "left";
$prg->body_color = "#C6DEFF";
$prg->body_textcolor = "#000000";
$prg->surrounded = '1';
//$prg->font_name = "Boishakhi";
mysql_connect("localhost","username","password");
mysql_select_db("my_database");
$res = mysql_query("select * from table");
$prg->mysql_resource = $res;
//$prg->title = "Test Table";
$prg->generateReport();
?>
OR
Can somebody show me a easier/more effective way to do this?
Here is the sample code that you can use to update your mysql database by sending request to the server to access process_mysql.php :
<select onchange="update_mysql();">
<option value="1">option 1 </option>
<option value="2">option 2 </option>
</select>
Jquery function with ajax post request:
<script>
update_mysql(){
var id = $('select option:selected').val();
$.ajax({
type:"post",
url:"process_mysql.php",
data:"id="+id,
success:function(data){
alert('Successfully updated mysql database');
}
});
}
</script>
<?php
$sql = "SELECT `docid`, `fullname` FROM `doctors` ORDER BY fullname ASC";
$result = $database->query($sql) or die('cannot connect to the database');
while($row = mysql_fetch_array($result))
{
echo"<option value= ".$row['docid'].">".$row['fullname']."</option>";
}
?>
This is my select box which i am populating through datbase table.
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
i want to make this one as SELECTED ITEM ON THE Select box
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>')
});
This is my jquery code. When i click ".sheUpdate" link i have couple of values that i am grabing using attr function. i am grabing depatment name and department value which i want to show as the SELECTED ITEM ON THE SELECT BOX
I think we need to see more code to be able to properly help. What is the html code of the element with the .sheUpdate class?
Does this link element actually have attributes dptname and dptid?
What is the code you use on #Deptmentselectbox?
The code you added is working properly.
just need to set the new added element as selected.
please check this fiddle
Also please let me know what value you get if you write this
alert($(this).attr('dptname'));
alert($(this).attr('dptid'));
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>')
$("#Deptmentselectbox").get(0).selectedIndex = 0;
// OR $("#Deptmentselectbox").val(deptid);
});
Assuming that your initial select box is like this:
<select id="Deptmentselectbox">
<option value=''> Select a department </option>
</select>
To remove the placeholder on first option selected:
$('.sheUpdate').click(function(){
var deptment = $(this).attr('dptname');
var deptid = $(this).attr('dptid');
if($("#Deptmentselectbox").val() == '')
$("#Deptmentselectbox").html('<option value='+deptid+'>'+deptment+'</option>');
else
$("#Deptmentselectbox").prepend('<option value='+deptid+'>'+deptment+'</option>');
$("#Deptmentselectbox").val(deptid);
}
Here is a Solution Hope it Helps
$(document).ready(function(){
$("#test1").click(function(){
var data = $("#t").val();
var data1 = $("#r").val();
$("#try").prepend('<option value='+data+' selected="selected">'+data1+'</option>');
});
});
Click Here For Demo