View customer info on select change - php

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})

Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>

<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.

Related

How to create checkboxs that fetch from database and pass on value

I am new to php and can not turn a row into a checkbox field that passes onto a separate page.
if ($result = $db->query($sql) ) {
//*start of original
if ($result->num_rows > 0) {
?>
<!-- <form action="Confirmation.php" method="post"> -->
<form action="Payment.php" method="post">
<label for="PatientID">Choose the Patient you wish to register for:</label>
<select name="PatientID" id="">
<option value="" disabled>Please select a patient to enroll:</option>
<!-- <option value="All">All Patients</option> -->
<?php
while($result = fetch_assoc($result)) {
echo "<input type='checkbox' value='{$row['PatientID']}'>" . $row['PatientName'] . '</br>';
}
//
//while ($row=$result->fetch_assoc()) {
?>
//<option value="<?=$row['PatientID'];?>"> <?=$row['PatientName']?></option>
//*/ <?php
//}
echo '</select><input type= "submit" class="myButton" name="submit" value="Register Now" /></form>';
} else {
echo "There are no patients currently available for registration." ;
$rosterListFail = true;
}
} else {
$message = $db->error;
// echo $message;
}
//*/
//}
?>

echo is showing output in page source instead of on page

I made a table in php and wanted to show the Id's in the dropdown select menu by making a separate file for php. So the code in main file is:
<?php include "functions.php";?>
<form action="login_update.php" method="post">
<div class="form-group">
<label for="username">username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<?php
showAllData();
echo "<br>"."askfkldfjl;adfafladfdf";
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="update">
</form>
The code of functions.php is :
<?php
function showAllData(){
$connection = mysqli_connect('localhost','root','****','loginapp');
if($connection){
echo "We are connected. a=".$a."<br>";
}else{
die("Database connection failed");
}
$query = "SELECT * FROM users";
$result = mysqli_query($connection,$query);
if($result){
echo("<br>"." <b><h6>We are successful</h6></b>");
}
else {
die("Query FAILED" . mysqli_error());
}
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
echo"<option value='$id'>$id</option>";
}
}
?>
The expected output was :
But the output is:
So the top two lines in the above screenshot are not printing.
These lines are shown in the INSPECT ELEMENT in chrome.
I forgot to mention the echo command:
echo "<br>"."askfkldfjl;adfafladfdf";
below show all data is also not working.
You made a mistake.
Actually you wrote a code in selectbox and you dont add option so thats why it is not show in html
So write a code like below code so its show in select box as option.
<div class="form-group">
<select name="id" id="">
<option> <?php
showAllData();
echo "<br>"."askfkldfjl;adfafladfdf";
?></option>
</select>
</div>
And If you want to show option from showAllData(); function, the you have return the html.
For this update your showAllData(); function with below code:
function showAllData(){
$options="";
$connection = mysqli_connect('localhost','root','****','loginapp');
if($connection){
echo "We are connected. a=".$a."<br>";
}else{
die("Database connection failed");
}
$query = "SELECT * FROM users";
$result = mysqli_query($connection,$query);
if($result){
echo("<br>"." <b><h6>We are successful</h6></b>");
}
else {
die("Query FAILED" . mysqli_error());
}
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$options.="<option value='$id'>$id</option>";
}
return $options;
}
Move the PHP function showAllData() before the HTML <select> element.
Because the <select> element awaits for an <option> element, but all another text will not be visible on page.
E.g.:
<div class="form-group">
<?php showAllData(); ?>
</div>
<?php
function showAllData(){
$connection = mysqli_connect('localhost','root','****','loginapp');
if($connection){
echo "We are connected. a=".$a."<br>";
}else{
die("Database connection failed");
}
$query = "SELECT * FROM users";
$result = mysqli_query($connection,$query);
if($result){
echo("<br>"." <b><h6>We are successful</h6></b>");
}
else {
die("Query FAILED" . mysqli_error());
}
echo '<select name="id" id="">';
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
echo"<option value='$id'>$id</option>";
}
echo "</select>";
}
?>
Your code is mixed up.
You can use below code. Create an array which gives you values which you needs to show in select.
<?php
function showAllData(){
$idArr = array('msg'=>'','data'=>'','status'=>0);
$connection = mysqli_connect('localhost','root','****','loginapp');
if($connection){
$idArr['msg'] = "We are connected";
$idArr['status'] = 1;
}else{
$idArr['msg'] = "Database connection failed";
$idArr['status'] = 0;
}
if($idArr['status'] == 1){
$query = "SELECT * FROM users";
$result = mysqli_query($connection,$query);
if($result){
$idArr['msg'] = "We are successful";
$idArr['status'] = 1;
}else {
$idArr['msg'] = "Query FAILED" . mysqli_error();
$idArr['status'] = 0;
}
if($idArr['status'] == 1){
while($row = mysqli_fetch_assoc($result)) {
$idArr['data'][] = $row["section_id"];
}
}
}
return $idArr;
}
$idArr = showAllData();
?>
<?php
if(!empty($idArr['data'])){
echo "We are connected<br>";
echo("<br>"." <b><h6>We are successful</h6></b>");
?>
<form action="login_update.php" method="post">
<div class="form-group">
<label for="username">username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<option value="0">--Select--</option>
<?php
foreach ($idArr['data'] as $key => $value) {
echo"<option value='$value'>$value</option>";
}
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="update">
</form>
<?php }else{
echo $idArr['msg'];
}
?>
Why you are putting <br> inside the select tag? select tag only accept the options tag under it, so please remove br tag and all extra strings inside the select tag. and you should echo the message above the select tag if you want to show your users.
Thanks

PHP if option is selected, selected option can't selected again in other chooses

Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js

dropdown list based on checkbox

i have few checkboxes named as HR,visitor,gaurd now i want to get which ever chckbox is selected according to it names of the employee belonging to that team whether HR or Guard or visitor to be shown in dropdown list
<select name=cmbname id="cmbname" width='50%'>
ALL
`
$objDB->SetQuery($sql);
$res = $objDB->GetQueryReference();
if(!$res)
exit("Error in SQL : $sql");
if($objDB->GetNumRows($res) > 0)
{
while($row = mysql_fetch_row($res))
{
print("
<option value='{$row[0]}'>{$row[0]}</option>");
}
}
mysql_free_result($res);
?>'
Himani ,
Try this. Hope it will be useful to you. Instead of text-area you can use drop-down.
Try this way gives you solution
<script type="text/javascript">
//javascript
function clicked_checkbox()
{
document.form.submit();
}
</script>
<?php
$hr = isset($_REQUEST['HR'])?$_REQUEST['HR']:false;
$guest = isset($_REQUEST['guest'])?$_REQUEST['guest']:false;
$visiter = isset($_REQUEST['visiter'])?$_REQUEST['visiter']:false;
//Prepare query with retrieved value and put value in Dropdown
$sql = 'select * from table ';
if($hr) { $sql .= "where user = '$hr'" };
if($guest) { $sql .= "where user = '$guest'" };
if($visiter) { $sql .= "where user = '$hr'" };
$objDB->SetQuery($sql);
$res = $objDB->GetQueryReference();
if(!$res)
exit("Error in SQL : $sql");
if($objDB->GetNumRows($res) > 0)
{
while($row = mysql_fetch_row($res))
{
print("<option value='{$row[0]}'>{$row[0]}</option>");
}
}
mysql_free_result($res);
?>
//on change of checkbox we'll call above function and set data to dropdown
<form name='form' method='get' action='#'>
<input type="checkbox" id="checkbox_HR" name="HR" value="true" <?php if($hr) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
<input type="checkbox" id="checkbox_guest" name="guest" value="true" <?php if($guest) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
<input type="checkbox" id="checkbox_user" name="visiter" value="true" <?php if($visiter) echo "checked='checked'"; ?> onchange="return clicked_checkbox();">
</form>
like this you can achieve :)

Field should still appear if there is no row in database

On my form, I have an echo which links to the data in my database.
However, If it is the first time the form has been visited (no ID in the table relating to the session) the textboxes do not appear whereas they should appear but empty!
It is successful when the id links to the session and there is a row in the database (the user has already completed the form once and has come back to edit.)
I hope this makes sense. To try and be clearer, if the user is visiting the form for the first time the textareas should be there (they disappear at the moment) but be empty.
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?>
</textarea>
Use mysql_num_rows()
<form action="thesis.php" method="post" name="regForm" id="regForm" >
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
//your textarea with values from database
<?php }
} else { ?>
//empty textares
<textarea></textarea>
<?php } ?>
Did you mean someting like this
Please try code given below it may be helpful..
<form action="thesis.php" method="post" name="regForm" id="regForm" >
<?php if (mysql_num_rows($rs_settings) <= 0) { ?>
<textarea name = "thesis_Name" type = "text" style = "width:500px; height:150px"
id = "thesis_Name" size = "600"></textarea>
<?php
} else {
while ($row_settings = mysql_fetch_array($rs_settings)) {
?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?>
</textarea>
<?php
}
}?>
Here mysql_num_rows($query) first check if result exist any row or not
but if form has multiple fields then
<?php
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = {$user_id}") or die(mysql_error());
$result = array();
if (mysql_num_rows($rs_settings) == 0) {
$result[0]['thesis_Name'] = "";
$result[0]['field1'] = "";
} else {
$i = 0;
while ($res = mysql_fetch_array($rs_settings)) {
$result[$i] = $res;
$i++;
}
}
foreach ($result AS $index => $r) {
?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $r['thesis_Name']; ?>
</textarea>
<?php } ?>

Categories