Pre Populating a PHP Dynamic Select Option with Stored Session Variable - php

Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy

Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>

You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.

Related

how to load a drop down with a query using the result from a previous drop down

It is early in my PHP and HTML career. I want to populate a with a SQL query - no problem. But then, take the highlighted value from that query and use it to drive another query with which to populate a different drop down.
What I don't understand is how the values are passed between the HTML and the PHP, should I use a global variable to store the selection from the first drop-down? How do I do this?
Is there any alternative to using a button to indicate that the current highlighted value in the first drop-down is to be used to drive the query which populates the second drop-down?
My code looks like this:
Asset type:<br/>
<select size=3 class="element select medium" id="WantAssetCategory" name="WantAsset Class">
<?
$sql = "SELECT * from Categories";
$result = $dbcon->query($sql);
foreach ($result as $row){
$catname = $row['description'];
$catx = $row['id'];
echo '<option value = ' . "$catx> $catname</option>" ;
}
$result = null;
?>
</select>
<select size=3 class="element select medium" id="WantAssetCategory" name="WantAsset Class">
Use jQuery to listen to the change on the select and perform the action script with the selected value, in response update the options for the new drop down with the mentioned id.
document.getElementById("WantAssetCategory").onchange = function() {
$.ajax({
data: this.value, // This is the selected value from your drop down.
type: "POST", // GET or POST
url: "query.php", // the file(where the query is) to call
success: function(response) {
$('#output').html(response);// repose response should contain the new select options and #output should be the id of the new select drop down.
}
});
}
I hope that helps.

Integrating href with $_GET value into a select option

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

Database entry multiple records

I have a table of inactive users displayed in a table from a mysqli database. I have then created a new row for each user and a cell for each row containing a dropmenu with 3 options - admin , delete user, activate user.
$stmt = $mysqli->prepare("SELECT username, firstname, lastname, registerdate FROM users WHERE level < 1");
$stmt->bind_param('ssss', $_GET['username'], $_GET['firstname'], $_GET['lastname'], $_GET['registerdate']);
$stmt->execute();
$stmt->bind_result($username, $firstname, $lastname, $registerdate);
?>
<table>
<tr>
<th colspan="7"><h1>Inactive Users</h1></th>
<tr>
<td><h2>Username</h2></td>
<td><h2>Firstname</h2></td>
<td><h2>Lastname</h2></td>
<td><h2>Date Registered</h2></td>
<td><h2>Days Inactive</h2></td>
<td><h2>Activate</h2></td>
<td><h2>Submit</h2></td>
<?php
while ($stmt->fetch()){
$today = new DateTime("now");
$registered = new DateTime($registerdate);
$dayspassed = date_diff($registered, $today);
echo '<tr class="'.$username.'">
<td>'.$username.'</td>
<td>'.$firstname.'</td>
<td>'.$lastname.'</td>
<td>'.$registered->format("d-m-y").'</td>
<td>'.$dayspassed->format("%a days").'</td>
<td>
<select name="'.$username.'" id="'.$username.'">
<option selected>Select Action</option>
<option value="activate">Activate User</option>
<option value="delete">Delete User</option>
<option value="admin">Admin</option>
</select>
</td>
<td><input type="submit" name="'submit'" value="Confirm" />
</td>';
}
$stmt->close();
?>
</table>
I'm trying to write some basic code that will be something like foreach dropmenu with the value "activate" insert user into table activated. Each select menu has the name of $username collected from the db table. So far i have something like this.
if(isset($_POST['submit']))
{
$activate = $_POST["activate"];
$delete = $_POST["delete"];
$admin = $_POST["admin"];
foreach ($username == $_POST["activate"]{
First of all, when handle $var equals $_POST, you need to check if $_POST is set, otherwise you'll get an error.
if(isset($_POST['activate'])) $activate = $_POST['activate'];
ok, then, if you select 4 users for example, if you want to handle it, you can use Ajax. with js turn off the default action on submit button, then take all ids for activate, all ids for delete and all ids for anything that you want and concat on an array like array['action_type']['user_id'];
then, you just send it by $_POST to another php to handle.
For better example explanation, you can get:
array['activate']['1'];
array['activate']['2'];
array['delete']['3'];
array['activate']['4'];
Or you can get
array['activate']['1,2,4'];
array['delete']['3'];
then you can activate users 1, 2 and 3, and delete user 4 in a loop (use what you like. while, do-while, for, foreach...)
Hope it helps!
Php for select:
<select name="'.$username.'" onchange="updateUser(this)" id="'.$username.'">
Then javascript (with jQuery):
function updateUser(param) {
var username = $(param).attr('id');
var action = $(param).val();
var phpDataPrepare = [username, action];
var phpData = JSON.stringify(phpDataPrepare);
$.ajax({
url:'<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . "?action=update_user"; ?>',
data: phpData,
type: 'POST',
success: function(data){
//data = response
//put any javascript here as a success function if needed.
}
});
}
Then just write the PHP to receive this information (near the top of the same page)
To get your information:
if(isset($_GET['action']){
if($_GET['action'] == 'update_user'){
$info = json_decode(file_get_contents('php://input'));
$username = $info[0];
$action = $info[1];
//Do what needs to be done
exit();
}
}

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.

Using Jquery, mysql, and php I need the results of one dropdown select to alter the choices in a second dropdown

I have 2 dropdown select boxes in my form. The first one allows the user to choose a car make "vmake". Once a vmake is chosen a "vmodel" select box appears from thin air and then the user can choose the vmodel. However, I want the vmodel box to be there on page load, so it doesnt just appear out of thin air. It would be empty if the user tries to open it until they select a vmake. Heres my html
<select name="vmake" id="vmake">
<option value"" selected="selected">Make</option>
<?php getTierOne()l ?>
</select>
<select name="vmodel" id="vmodel">
<option value"" selected="selected">Model</option>
</select>
<span id="wait_1"></span>
<span id="result_1"></span>
Heres the jquery:
$(document).ready(function(){
$('#wait_1').show();
$('#vmake').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func" "vmake",
drop_varL $('#vmake').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout(finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
]);
});
lastly the php which connects to my database
function getTierOne()
{
$result = mysql_query("SELECT DISTINT vmake FROM vmake")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{ echo '<option value="'.tier['vmake'].'">'.$tier['vmake'].'</option>';
}}
if($_GET['func'] == "vmake" && isset ($_GET['func'])) {
vmake($_GET['drop_var']);}
function vmake($drop_var)
{ include_once('db.php');
$result = mysql_query("SELECT * FROM vmake WHERE vmake='$drop_var'")
or die(mysql_error());
echo '<option value=" " selected="selected">Model</option>';
while($drop_2 = mysql_fetch_array( $result))
{ echo '<option value="'.$drop_2['vmodel'].'">'.$drop_2['vmodel'].'</option>';
}}
I got some help with the original code form an open source website and now I just need to change it a little to make it do what I want. As it stands it will create a new vmodel select box next to the existing one, but I just want it to populate the select box that appears on page load. Any help is very much appreciated. Thanks for everything.
Did you try using jQuery .load?
Example:
$('#vmodel').load('func.php',{vmake:$('#vmake').val()});
Would need to change the PHP as well, so you make a normal array of values and then send it through json_encode().

Categories