I want to fetch all the records by filtering a role from a dropdown list. This was working perfectly.
(1) But I want to display all the records by default, only when I select the role, all the role users should be filtered.
(2) I want to make my code shorten instead of writing the code two pages, could we fetch all the data from members.php, instead of using memlist.php again.
members.php
<html>
<head>
<script type="text/javascript" src="js/jqueryv1.10.2.js"></script>
<script type="text/javascript">
function showUser(str)
{
document.getElementById("getrole").style.display="block";
if (str =="")
{
document.getElementById("getrole").innerHTML="";
return;
}
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status == 200) { document.getElementById("getrole").innerHTML = xmlhttp.responseText; }
}
xmlhttp.open("GET","memlist.php?role="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo 'Select the role : <select name="users" onchange="showUser(this.value)">';
$sel_role = $db->query('SELECT * FROM role');
$sel_role->execute();
echo '<option selected="selected">Select a role</option>';
while ($row = $sel_role->fetch(PDO::FETCH_ASSOC))
{
$role_id = $row['role_id'];
$role_name = $row['role_name'];
echo '<option value='.$role_id.'>'.$role_name.'</option>';
}
echo '</select>';
echo '<div id="getrole"></div><input type="hidden" value='.$role_id.'>';
?>
</body>
</html>
memlist.php
<?php
require 'init.php';
$uid = $_GET['role'];
$dis_role = $db->prepare('SELECT bu.*, br.* FROM users bu JOIN role br ON bu.role_id = br.role_id WHERE br.id = '.$uid.'');
$dis_role->execute();
echo '<table id="result">
<tr><th><label>USERNAME</label></th>
<th><label>ROLE</label></th>
</tr>';
foreach($dis_role as $dr)
{
echo '<tr>
<td>'.$dr['username'].'</td>
<td>'.$dr['role_name'].'</td>
</tr>';
}
echo '</table>';
?>
Related
I have a MySQL Database on a Server. This is how my HTML stores thing in that DB
var shV = localStorage.getItem("PersName");
var idV = localStorage.getItem("codeQR");
var posV = localStorage.getItem("position");
window.open('http://*.es/insert.php?sh='+shV+'&id='+idV+'&pos='+posV,
'blank','location=no,hidden=yes,closebuttoncaption=Done,toolbar=no');
The Insert.PHP File
<?php
try {
$pdo = new PDO('mysql:host=mysql.**');
$shortV = $_GET['sh'];
$idnumberV = $_GET['id'];
$positionV = $_GET['pos'];
$statement = $pdo->prepare("INSERT INTO idtabelle (short, idnumber, position)
VALUES (:sh, :id, :pos)");
$statement->execute(array('sh' => $shortV, 'id' => $idnumberV, 'pos' => $positionV));
echo "$idnumberV eingetragen";
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
?>
I want to store them without opening a new Page or show them the Insert Url. After it is in the DB i want a Feedback like "Your Data has been entered" only when they are really in the DB.
In an other HTML I search the Position by entering an ID in an Textfield. It works like I want. In the Page and a Feedback is given.
Search.html
<form id="search" name="search" method="post">
<input type="text" id="txt1" name="search_input">
<button type="submit" class="btn btn-info" id="bt1">Get Position</button>
</form>
<div id="div1">Testing</div>
<div id="div2"> Here </div>
<script>
$(document).ready(function(){
$("#search").on("submit", function(e){
e.preventDefault();
$.post("/search3.php", $("#search").serialize(), function(d){
if (!$.trim(d)){
alert("Nothing found !"); }
else{
$("#div1").empty().append(d);
localStorage.setItem("PosGet",d);
document.getElementById("div2").innerHTML=(d);
}
});
});
});
The Search.PHP File
<?php
try {
$pdo = new PDO('mysql:host=mysql.**');
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty');
$statement = $pdo->prepare("SELECT position, short FROM idtabelle WHERE idnumber = ?");
$statement->bindParam(1, $idV);
$statement->execute();
foreach($statement -> fetchAll() as $row){
echo $row['position'];
}
$pdo = null;
} catch (PDOException $e) {
die($e -> getMessage());
}
?>
How can I do it that the Insert is like the Search above in the Page and with a Feedback?
Thank you.
in your first example the code runs a new window (but hidden), so you have no chance to get a result from the inital window. You should do it like in the second provided example.
If you can use jQuery ( your examples looks like) you can use the jQuery.ajax() function
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
You also can have a success and a failure callback. Example:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
function(){
console.log("success");
},
function(){
console.log("error")
}
})
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$dbconn = pg_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect');
}
$query = "SELECT * FROM user WHERE id = $1";
$result = pg_prepare($dbconn, "my_query", $query);
$data = array($q);
$result = pg_execute($dbconn, "my_query", $data);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = pg_fetch_row($result)) {
echo "<tr>";
echo "<td>" . $row[0] . "</td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "<td>" . $row[3] . "</td>";
echo "<td>" . $row[4] . "</td>";
echo "</tr>";
}
echo "</table>";
pg_close($dbconn);
?>
</body>
</html>
The Html
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
This is a simple example using PostgreSQL, for you to understand the basics. If you want more help start programming, and if you have any difficulties ask the community.
In the example above, when a user selects a person in the dropdown list above, a function called "showUser()" is executed.
The function is triggered by the onchange event.
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint and exit the function. If a person is selected, do the following:
1) Create an XMLHttpRequest object
2) Create the function to be executed when the server response is ready
3) Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the dropdown list)
The page on the server called by the JavaScript above is a PHP file called "getuser.php".
The source code in "getuser.php" runs a preaper execute on a PostgreSQL database, and returns the result in an HTML table.
Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:
1) PHP opens a connection to a PostgreSQL server
2) The correct person is found
3) An HTML table is created, filled with data, and sent back to the "txtHint" placeholder.
I want to display data from database when I select an option from a dropdown option in php
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<?php
include("db_connection.php");
$name="select name from supplier_name";
?>
<form method="POST" action="getuser.php">
<tr>
<td>Name</td>
<td><?php echo "<select name='name'
onchange='showUser(this.name)'><option value=''>select
name</option>";
foreach ($con->query(#$name)as $ridyn)
{
echo "<option value='$ridyn[name]'>$ridyn[name]</option>";
}
echo"</select>"; ?></td>
</tr>
</form>
<br>
<div id="txtHint"><b>You have selected......</b></div>
</body>
</html>
Here is a jQuery example (I am not really familiar with straight javascript ajax). You should be able to fill it in from this example.
// Have a function that returns your names
function getSuppliers($con)
{
$query = $con->query("select `name` from `supplier_name`");
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
$row[] = $result;
}
return (!empty($row))? $row : array();
}
// Include database con at top
include("db_connection.php");
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function(){
// On menu-change
$(this).on('change','.ajax_change',function(e){
$.ajax({
// Get the url from the action on the form
url: $('#getUser').attr('action'),
// Get the value of the dropdown
data: { value: $(this).val() },
type: 'post',
success: function(response) {
// Print to the text-hint div
$('#txtHint').html(response);
}
});
});
});
</script>
</head>
<body>
<form method="POST" action="getuser.php" id="getUser">
<table>
<tr>
<td>Name</td>
<td>
<select name='name' class="ajax_change">
<option value=''>Select name</option>
<?php foreach(getSuppliers($con) as $ridyn) {
?> <option value="<?php echo $ridyn['name']; ?>"><?php echo $ridyn['name']; ?></option>
<?php }
?> </select>
</td>
</tr>
</table>
</form>
<br />
<div id="txtHint"><b>You have selected......</b></div>
</body>
</html>
what i'm trying to doing is when user click on php select option.then
it's value should pass to another page as variable.
there is a code i'm
trying.
<table>
<tr><td>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("member")or die(mysql_error());
$result = mysql_query("SELECT id,ugroup FROM ugroups");
?>
<select name='group' id='group' >
<?php
while ($line = mysql_fetch_array($result)) {
echo '<option value=' . $line['ugroup'] . '>' . $line['ugroup'] . '</option>';
}?>
</select>
click
</td></tr>
</table>
this is add_group.php code
<?php
session_start();
ob_start();
include('../limoconfig.php');
if(!isset($_SESSION['adminuserid']) )
{
header('Location:../index.php');
}
else
{
if($_GET)
{
$ugroup = $_GET['ugroup'];
/*$id = $_GET['id'];*/
$acc_status = "update users set ugroup='".$ugroup."' where id=1931";
echo $acc_status;
$rate = db::getInstance()->exec($acc_status);
header('Location:../home.php');
}
}
?>
it's not working.
First of all you need to put your table within
and then you can call ajax on click of your anchor ().
jQuery(document).ready(function($) {
var data='';
$("#group option:selected").each(function() {
if ($(this).attr('value') !== '') {
data=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
type: "POST",
url: "file.php",
data: data,
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
Wrap it in a form tag and create a submit button instead of the link and it can send it in either POST or GET.
The element is a form control and can be used in a form to collect user input.
http://www.w3schools.com/tags/tag_select.asp
you can either do it with ajax or just using html forms.
eg of ajax : Just a simple eg, you can modify according to your need
<html>
<head>
function myAjax(str)
{
if (str=="")
{
document.getElementById("results").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","add_group.php?ugroup="+str,true); // your next page
xmlhttp.send();
}
function myFunction() {
var x = document.getElementById("group").value;
myAjax(x);
}
</script>
</head>
<body>
<table>
<tr><td>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("member")or die(mysql_error());
$result = mysql_query("SELECT id,ugroup FROM ugroups");
?>
<select name='group' id='group' >
<?php
while ($line = mysql_fetch_array($result)) {
echo '<option value=' . $line['ugroup'] . '>' . $line['ugroup'] . '</option>';
}?>
</select>
click
</td></tr>
</table>
<div id="results"> <!-- the echo of add_group.php gets displayed here --> </div>
</body>
</html>
I used Ajax and abc.php(code for it is below) to populate the values of second select tag but i am not able to populate the third select tag which should appear after the selection of the second select tag. Any suggestion would be highly appreciated
<?php
$q=$_GET["q"];
include "localhost.php";
$sql="SELECT * FROM books WHERE class = '".$q."'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo "<select name=\"name\">
<option>Select subject
</option>";
echo "<option>" . $row['name'] ."</option>";
echo "</select>";
}
}
else
{
echo "error";
}
mysql_close($con);
?>
my html code is
<?php
include "menu.php";
include "localhost.php";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
<!--Code for selecting class-->
function showUser(str)
{
if (str=="Select class:")
{
document.getElementById("txtHint").innerHTML="Select any class";
return;
}
if (str=="Select cla:")
{
document.getElementById("txtHint1").innerHTML="Select any cla";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","select11.php?q="+str,true);
xmlhttp.send();
}
<!--End of Code for selecting class-->
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link type="text/css" href="style.css" rel="stylesheet" />
</head>
<body>
<div id="sn">
<ul class="crumbs">
<li class="first"><span></span>Home</li>
<li>Books</li>
<li>Sale Books</li>
</ul>
</div>
<div id="newad">
<fieldset>
<legend><strong>Sale Books & Stationary</strong></legend>
<form >
<table width="499" >
<tr>
<td width="96">Select Class:</td>
<td width="139"><select required="required" x-moz-errormessage="Select the Class" name="class" id="select" onchange="showUser(this.value)">
<option selected="selected">Select class:</option>
blah blah
And yes i know sir that the while loop will give me ennumerous select tags.
it should be
if(mysql_num_rows($result) > 0)
{
echo "<select name=\"name\"><option>Select subject</option>";
while($row = mysql_fetch_array($result))
{
echo "<option>" . $row['name'] ."</option>";
}
echo "</select>";
}
Can you show your html?
Try to add onchange="someFunction()" in the second select tag, where someFunction() is a javascript function that uses ajax to populate the third select.
Your question makes no sense, but can I suggest you check your variables are set before using and clean up the sql-injection you have example.com?q=' or '1=1. Currently what your code will do is create a new select box for every result returned, you need to initialize the select outside the loop then insert the option within the loop:
<?php
$q = !empty($_GET["q"])?$_GET["q"]:null;
include "localhost.php";
if($q != null){
$sql="SELECT * FROM books WHERE class = '".mysql_real_escape_string($q)."'";
$result = mysql_query($sql);
$sel = '<select name="name"><option>Select subject</option>';
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
$sel .= "<option>" . $row['name'] ."</option>";
}
}else{
$sel .= '<option>No Books</option>';
}
$sel .= "</select>";
echo $sel;
}
?>
I have been trying for a while to find out a correct method of pulling information from a database based on the initial text
selected on a html drop down menu.
Here is my code:
<html>
<head>
</head>
<script src="testjs.js"></script>
<?php
$host = "";
$username = "";
$password = "";
$database = "";
mysql_connect($host, $username, $password);
mysql_select_db($database);
?>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<?php
$Query = mysql_query("SELECT * FROM population");
while ($Rows = mysql_fetch_array($Query))
{
$ID = $Rows['ID'];
$Pop = $Rows['Pop'];
$UniqueID = $Rows['uid'];
echo "<option value=\"$UniqueID\">$Pop</option>";
}
?>
</select>
</form>
<br>
<p>DB ID <input type="text" id="ids" name="ID" ></p>
<p>Population <input type="text" id="content" name="contet" ></p>
<p>Unique ID <input type="text" id="uid" name="uid" ></p>
<div id="GetInformation"><b>Person info will be listed here.</b></div>
</body>
</html>
test.js contains:
function showUser(str)
{
if (str=="")
{
document.getElementById("GetInformation").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("GetInformation").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
Get user contains:
<?php
$q=$_GET["q"];
$con = mysql_connect('', '', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DropDown", $con);
$sql="SELECT * FROM population WHERE uid = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
?>
<script type="text/javascript">
var ids = '<?php echo json_encode($ID); ?>';
var content = '<?php echo json_encode($Pop); ?>';
var uid = '<?php echo json_encode($UID); ?>';
</script>
<?php }
mysql_close($con);
?>
try changing
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
?>
<script type="text/javascript">
var ids = '<?php echo json_encode($ID); ?>';
var content = '<?php echo json_encode($Pop); ?>';
var uid = '<?php echo json_encode($UID); ?>';
</script>
<?php }
to
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
echo $ID . ' - ' . $Pop . ' - ' . $UID;
}
this should work. but there are better ways as they give you more access later on in your client side. e.g. send a JSON object back, a quick example would be:
$info = array();
while($row = mysql_fetch_array($result))
{
$ID = $row['ID'];
$Pop = $row['Pop'];
$UID = $row['uid'];
$info[] = array( 'id' => $ID, 'pop' => $Pop, 'uid' => $UID );
}
echo json_encode($info);
and your JS would be something like :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("GetInformation").innerHTML += data[i].id + ' - ' + data[i].pop + ' - ' + data[i].uid;
}
}
NOTE: if you are working with a browser that doesn't include the JSON library you need to load http://www.json.org/js.html . Also your AJAX/DOM changes can become much simpler if you want to use jQuery