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>
Related
Is that possible to select variable in DB (such as : $username) and display their info in textbox ?
Example:
Select : $username
after the selection, in the text input , will show:
$username , $usernameEmail , $usernameContactNumber
and click on "Register", it will insert to database with the information
I have no idea how does this work. I have no problem in inserting value to database.
The only problem that I am unable to solve right now is the condition I needed.
When I choose $username (example: userA),
all the information of userA will be appearing in the text input below
$query = "SELECT * FROM userdatabase";
$result1 = mysqli_query($db,$query);
<select>
<?php while($row1 = mysqli_fetch_array($result1)):; ?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[2];?></option>
<?php endwhile;?>
</select>
The code above is the selection (PHP
<script>
$(document).ready(function(){
$("form#get").submit(function(event) {
event.preventDefault();
var input = $("#username");
$.ajax({
type: "POST",
url: "userregisteraccount.php",
success: function(data) { input.val(data); }
});
});
});
</script>
code above is the ajax
so that when i choose "userName" , "userName" data will be show in the registerform
I have a basic form that I would like to have other fields appear underneath such as email address and job title when the user is selected from the drop down.
The process will be:
User selects name from the drop down
PHP, JQUERY to query mysql database where user is equal to the selection from dropdown
Email address and Job Title fields to appear underneath with populated information.
My JQuery doesn't seem to work on my page...
I have used the code from this Stack Overflow question in which my reply was removed because it was not a 'solution': Populate input fields with values when option is selected - php mysql
Any help on this would be appreciated!
self_submit.html
<html>
<head>
<title>TEST</title>
<script>
$(document).ready(function(){
$('#user').on('change',function(){
var user = $(this).val();
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
async : false,
data : { user : user},
success : function(data) {
userData = json.parse(data);
$('#age').val(userData.age);
$('#email').val(userData.email);
}
});
});
});
</script>
</head>
<body>
<form>
User
<select name="user" id="user">
<option>-- Select User --</option>
<option value="username1">name1</option>
<option value="username1">name2</option>
<option value="username1">name3</option>
</select>
<p>
Age
<input type="text" name="jobtitle" id="jobtitle">
</p>
<p>
Email
<input type="text" name="email" id="email">
</p>
</form>
</body>
</html>
getUser.php
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$user = $_GET['user'];
$sql = mysqli_query($link, "SELECT jobtitle, email FROM tblusers WHERE username = '".$user."' ");
$row = mysqli_fetch_array($sql);
json_encode($row);die;
?>
Thanks in advance
you need to change your ajax call to:
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
data : { user : user },
success : function(data) {
userData = json.parse(data);
// $('#age').val(userData.age);
$('#jobtitle').val(userData.jobtitle); // Since you are selecting jobtitle, not age
$('#email').val(userData.email);
}
});
And also you forgot to echo your data:
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$user = $_REQUEST['user'];
$sql = mysqli_query($link, "SELECT jobtitle, email FROM tblusers WHERE username = '".$user."' ");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
exit();
?>
Hope this helps!
Define "POST" method in form tag
download jquery library for offline use or use google cdn or microsoft -then reference it in head html tag
change the data in ajax to data: "user="+user, am used to this format
lastly use proper id names correctly, incorrectly referencing 'ids', you reference in html email id =
$('#jobtitle').val(userData.age);
instead of
$('#email').val(userData.age)
this is fine =>
$('#email').val(userData.email);
$user = $_GET['user']; change to $user = $_POST['user'];
These are some mistake I observed without running you code if still you run into problems ask then
I am trying to get some data of a certain item selected in a select option and automatically display it on the textfield as shown in this image:
But it is not working. Is there a remedy for this or such type of coding is not workable at all? Hopefully someone can help me on this.
Here is the code I made:
$credit_accounts = $db->query("SELECT * FROM credits");
echo'<select id="customer_order_id" name = "customer_order_id">
<option value = "">SELECT ACCOUNT</option>';
foreach($credit_accounts as $key){
$id = $key['purchase_order_id'];
$name = $key['customer_firstName']."\t\t".$key['customer_lastName'];
echo'<option value = "'.$id.'">'.$name.'</option>';
}
echo'
</select>';
Note: The link will execute a query that will retrieve certain data of the selected item. If link is declared outside the loop without the <option></option> tag, it works accordingly. But if it is place within the loop of course with the <option></option> tag, it is not working like a link at all. Please help me out.
Sorry for my english , I will write some long answer hopefully it will also help others,so i am giving solution for doing following.
Please not : this solution is written and use SIMPLE MYSQL,AJAX and PHP function If you further want DATA SECURITY refer [PHP MySQLI Prevent SQL Injection
Objective : To get/display DATA from DATABASE related to a particular(ly 1) user/product and then fetch/display it in HTML page (additionally: without page refresh ) IN A FORM.
CODE :
<?php
//php-database connection script
$db_config = mysqli_connect("localhost", "username", "pass", "database_name");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
<?php
//this pHP SCRIP FIRES when you select a USERNAME (if u want not to SELECT but type then change ONCHANGE to ONKEYUP function & change username input type to text)
if(isset($_POST['uname'])){
$u = $_POST['uname'];
$sql = "SELECT email , gender FROM credits WHERE username='$u' LIMIT 1";
$query= mysqli_query($db_config,$sql);
while($row2 = mysqli_fetch_array($query)){
//Here we form a STRING SEPRATED BY QUAMMAS and ECHO IT TO PAGE
//later on we will fill this data in input fields
echo $row2['email'].",".$row2['gender'];
exit();
}exit();}
?>
<!-- HERE is your form where user will select or type his username-->
<form >
Select username :<br/>
<select id="user_name" onchange="load_data()">
<option value=""> select an ouser</option>
<option value="v1111"> v111</option>
</select><br/>
Email<br/>
<input type ="text" id="email" value=""><br/>
Gender :
<select id="gender">
<option value='m'>male</option>
<option value='f'>female</option>
</select>
</form>
<span id='status' ></span>
<script>
//AJAX OBJECT CREATION script it works as get or post mechanism
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
//here is function which fires when username is selected
function load_data(){
var value = document.getElementById('user_name').value;
//declare ajax obj, and name(url) of same page you are coding.
var ajax = ajaxObj("POST", "url.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var str = ajax.responseText;
//split STRING and extract individual data
var res = str.split(',');
//here we fetch his username into input field BINGO!do same for gender.
_('email').value = res[0];
//res[1] will have gender related data.
}
}
//Declaration to send URL encoded variable (username in this case)
ajax.send("uname="+value);
}
</script>
If you want further resources and info about data security see BRAD's comments in comments section
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 :)
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>