how to display the two different columns from the selected year - php

I do not know how will I display the position and names of the officers from year selected by the user.
Edit:
I used ajax now, but I'm still having a problem. When I click the combobox and select a year, the officers still don't show up. Only the table with the header Position and Name that shows up, but no data from my database under those columns.
getyear.php
<?php
$q = strval($_GET['q']);
$con = mysqli_connect('localhost','root','','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM officers WHERE year = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Position</th>
<th>Name</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['position'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
main.php
<form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$sql = "SELECT DISTINCT year FROM officers ORDER BY year DESC";
$result = mysql_query($sql);
/* assign an onchange event handler */
echo "<select name='year' onchange='showofficers(this.value)'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['year'] ."'>" . $row['year'];
}
echo "</select> <br>";
?>
<div id="txtHint">
</div>
</form>
<script>
/* event handler ~ no ajax function shown */
function showofficers(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","getyear.php?q="+str,true);
xmlhttp.send();
}
}
</script>

some pseudo-code o give you an idea of how you could achieve the desired goal.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$sql = "SELECT DISTINCT year FROM officers ORDER BY year DESC";
$result = mysql_query($sql);
/* assign an onchange event handler */
echo "<select name='year' onchange='showofficers(this.value)'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['year'] ."'>" . $row['year'];
}
echo "</select> <br>";
?>
<script>
/* event handler ~ no ajax function shown */
function showofficers( value ){
/*
use ajax to send a request that fetches the officers details
based upon the year selected. Preferred method=POST for ajax query
*/
alert( 'send '+value+' via ajax, build the sql query and use the ajax callback to generate the new html content' );
}
</script>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/* Intercept and process ajax request */
/* the year is POSTed by ajax */
$year = $_POST['year'];
$sql='select * from table where year='.$year;
$res=$db->query( $sql );
if( $res ){
/* process recordset and send back response */
}
}
?>

Related

problems with ajax, only displays the header and not the records

I have a problem with this code.
I created a drop-down menu that directly takes the categories from the database. so far everything is ok.
When, however, I choose the type, it only displays the header of the table and not the records.
can you tell me why?
I think the problem is "q" but I do not know how to modify it becouse I tried to do the query without 'Where' and correctly displays the records.
<html>
<script>
var xmlhttp;
function mostraInfo(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="2.php";
url=url+"?q="+str;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("info").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
<form>
Seleziona Categoria:
<select name="users" onChange="mostraInfo(this.value)">
<option value="">Seleziona categoria:</option>
<?php
//Seleziono quelli che sono i dipendenti
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$query = "SELECT distinct tipologia FROM gruppi ORDER BY tipologia ASC";
$result = mysql_query($query);
while($riga = mysql_fetch_array($result)){
echo "<option value='$riga[nome_gruppo]'> $riga[tipologia] </option>";
}
?>
</select>
</form>
<br />
<div id="info"></div>
</html>
----- file 2(2.php)------
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
$result = mysql_query($sql);
echo "<table border='2'>
<tr>
<th> Nome Gruppo </th>
<th> Email </th>
<th> Tipologia </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['nome_gruppo'] . "</td>";
echo "<td>" . $row['email_gruppo'] . "</td>";
echo "<td>" . $row['tipologia'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
It seems your problem is the query,you are using double quotation inside single quote, Try this instead :
$sql="SELECT * FROM gruppi WHERE tipologia = '{$q}'" ;
From the code, you've provided, I don't see where is $q defined.
So I believe in the end your query looks like:
"SELECT * FROM gruppi WHERE tipologia = ''"
You can always dump something in order to check what's really going on by inserting temporary code like this:
var_dump($sql);exit;
Just don't forget to remove/comment it after debugging ;)
Solution:
You need to get "q" parameter from the GET request:
$q = mysql_real_escape_string($_GET['q'], $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
mysql_real_escape_string function is there to prevent some simple SQL injections. Please check this out http://php.net/manual/en/function.mysql-real-escape-string.php
But it would be better to use at least PDO class instead of outdated "mysql_" functions.
Complete code of 2.php with fix:
$dbhost="localhost";
$dbname="my_lisipcivicsense";
$dbuser="lisipcivicsense";
$dbpsw="";
$con = mysql_connect($dbhost, $dbname, $dbpsw);
mysql_select_db($dbname, $con);
$q = mysql_real_escape_string($_GET['q'], $con);
$sql="SELECT * FROM gruppi WHERE tipologia = '".$q."'" ;
$result = mysql_query($sql);
echo "<table border='2'>
<tr>
<th> Nome Gruppo </th>
<th> Email </th>
<th> Tipologia </th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['nome_gruppo'] . "</td>";
echo "<td>" . $row['email_gruppo'] . "</td>";
echo "<td>" . $row['tipologia'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>

Getting the drop-down menu selected item and using it in php

I have the following drop-down list that fetches a list coalitions from the database (this list is populated as expected)
<form style = "display: inline-block;" >
<select class="form-control" name ="coalition_select" onchange = "showCandidates(this.value)" method="GET">
<option id = "coalition_id" value="coalition">Coalitions</option>
<?php
include_once 'connection.php';
$sql_coalition = mysqli_query($conn, "SELECT coalition FROM candidates");
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
}
?>
</select>
</form>
The problem begins here. Here I'm trying to first get the selected value (which is on of the coalitions) from the drop-down list and second use the value to display users with similar coalition attribute.
here is the script to get the value from the drop-down:
<script>
function showCandidates (str) {
if (str.length == "") {
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","includes/admin.users.list.inc.php?q="+str,true);
xmlhttp.send();
}
}
</script>
and here is the admin.users.list.inc.php file
<body>
<?php
$q = $_GET['q'];
$conn = mysqli_connect('localhost','root','','voting');
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
mysqli_select_db($conn,"osako_Voting");
$sql="SELECT * FROM candidates WHERE coalition = '".$q."'";
$result = mysqli_query($conn,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Coalition</th>
<th>Email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['coalition'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
</body>
The problem seem to be that I'm unable to set the variable $q so that it captures the selected value. right now as it is set it seems to capture the index instead of the value itself. How can this be correctly done? If it is of any help, I'm using this tutorial as a guideline
https://www.w3schools.com/php/php_ajax_database.asp
IN SUMMERY:
If we have a drop-down list that has been populated dynamically using php script. How can be get the selected value using ajax and use the said value in another php script.
Thanks
It seems the problem is in this row:
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
You're passing the select value to showCandidates(), to be passed via AJAX but you're setting the option value to be always static "coalition" and not the dynamic values you're fetching from DB.
Maybe you should change the row to
echo "<option value=\"" . $row['coalition'] . "\">" . $row['coalition'] . "</option>";
your not setting value to value attribute . your just setting constant string for all option values coalition
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"$row['coalition']\">" . $row['coalition'] . "</option>";
}
I know you have accepted an answer but i am puzzled as to this;
in your function you have this
document.getElementById("txtHint").innerHTML = "";
But you don't have any form element with the id "txtHint"
So what element is being sort with that ID?

AJAX script not parsing variable to php correctly

UPDATE 19/01/2017 - PROBLEM RESOLVED - Removed 'intval' on get request within get.php file and the value q is now capturing the correct data.
What i'm trying to achieve can be summed up in 2 points:
1.) A dropdown box which dynamically populates according to a MySql table
2.) Depending on whats chosen in the dropdown the textfield below will display a corresponding id via a SQL query.
I've been trying to follow W3Schools guide and modifying it accordingly to match my needs, but i'm getting stuck.
Here is what I currently have:
PHP -
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('core_log');
$sql = "SELECT local_authority FROM ons_code_tbl";
$result = mysql_query($sql);
echo "<tr>";
echo "<td> Local Authority: </td>";
echo "<td>";
echo "<select name='local_authority'onchange='showLocal_authority(this.value)'>";
echo '<option value=""></option>';
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['local_authority'] . "'>" . $row['local_authority'] . "</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
?>
Script -
<script>
function showLocal_authority(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","get.php?q="+str,true);
xmlhttp.send();
}
}
</script>
get.php -
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','core_log');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ons_code_tbl");
$sql="SELECT ons_code FROM ons_code_tbl WHERE local_authority = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$name = $row['ons_code'];
echo "<td>" . $q . "</td>";
mysqli_close($con);
?>
I did a test and simply echoed the value q to see what its outputting, it should be the value of whatever they pick in the dropdown, but instead its displaying 0?
In the screenshot below, it should display 'Amber Valley' with the correct ONS code pulled from the MySQL table.
If anyone can tell me why the value q is not storing 'Amber Valley' for example, that would be great, thanks!
Replace this line:
$q = intval($_GET['q']);
for
$q = $_GET['q'];
Then make a query with prepared statement, to avoid SQL Injection:
mysqli_select_db($con,"ons_code_tbl");
$sql="SELECT ons_code FROM ons_code_tbl WHERE local_authority = ?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "s", $q);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $ons_code);
mysqli_stmt_fetch($stmt);
Just replace echo "<td>" . $q . "</td>"; for echo "<td>" . $ons_code . "</td>";

Ajax refine search

I have a table for a sports day where there are 4 columns name, house, event, result. I have no problem creating and displaying the database but i want to be able to search in a bar and to use AJAX to automatically search all 4 columns for whats in the search bar. I am using PHPmyadmin to store the database with mySQLI. i am able to display the database on the page that i want. I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search. I have never used Ajax before so sorry for my bad code as it is all from w3schools site. the DB is called sports_day and the table is called full_results. here is my current code.
<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","results_query.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
and on a page called results_query.php is this code
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql="SELECT * FROM full_results WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
at the moment what happens is none of the table is shown and when i type anything in the search box the whole table appears along with in plain text at the bottom the title and all the contents of the table in a long line.
any suggestion to get my code to work would be greatly appreciated!
thanks!
The solution would be like this:
Keep your HTML search form as it is.
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
... I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search.
See this <div> section here,
<div class="col-sm-12">
...
</div>
You didn't put anything in this <div> section. First of all, you have to display your entire table in this section, which you can later filter out using the AJAX request. Also, assign an id to this <div> section so that it could be easier for you put the AJAX response in this <div> section. So the code for this <div> section would be like this:
<div class="col-sm-12" id="pupil-info">
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
Change your Javascript/AJAX code in the following way,
<script>
function showUser(str){
var str = str.trim();
var xmlhttp;
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("pupil-info").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
Please note that you should encode the user inputted str value using encodeURIComponent() function before passing it to the results_query.php page.
Finally, on results_query.php page process your AJAX request like this:
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
if(isset($_GET['q']) && !empty($_GET['q'])){
$sql .= " WHERE CONCAT(id, NAME, HOUSE, EVENT, RESULT) LIKE '%".$_GET['q']."%'";
}
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
}else{
echo "<tr>";
echo "<td colspan='4' style='text-align:center;'>No records found</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
If you use your 'results_query.php' file only for getting the data from database, then you don't need to create a <body> tag. If you use only PHP then you can easily skip any plane HTML. That's just a digression :)
But to the point.
You can change the way you return your data from database. I think, instead of doing a lot of echo's it is better to add result to the variable and echoing the variable at the end.
$data = '<tr>' . '<th>NAME</th>' . '<th>HOUSE</th>' . '<th>EVENT</th>' . '<th>RESULT</th>' . '</tr>';
while($row = mysqli_fetch_array($result)) {
$data .= '<tr>';
$data .= '<td>' . $row['NAME'] . '</td>';
$data .= '<td>' . $row['HOUSE'] . '</td>';
$data .= '<td>' . $row['EVENT'] . '</td>';
$data .= '<td>' . $row['RESULT'] . '</td>';
$data .= '</tr>';
}
$data .= '</table>';
mysqli_close($con);
echo $data;
See if this changes something.
What about showing entire table after the page's loaded, you will have to change both PHP and JavaScript code a little bit.
You can change your JS so it gets everything from your full_results table after page is loaded.
There are several ways to do this and you can read about them here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The easiest way would be to do this this way:
<script>
function showUser(str) {
var url;
var xmlhttp;
if (str == "") { //if empty string - get all data
url = "results_query.php";
} else { //get particular data otherwise
url = "results_query.php?q="+str;
}
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", url, true);
xmlhttp.send();
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
<script>
//calling your function with empty string because we want to get all data
showUser("");
</script>
and in the PHP file you can do something like this:
<?php
$q = 0;
//check if 'q' parameter was passed
if(isset($_GET['q'])) {
$q = intval($_GET['q']);
}
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";
Now your JavaScript function will be called after loading your page.
It will call your PHP script with AJAX and this script should return all data from your table.
In line ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results"; there is a simple check if $q is different from 0. Our variable will be set to 0 if no argument was passed, so whenever $q is equal to '0', we just want to get all the data from full_results and specific data otherwise.
I also added var xmlhttp because it is only local variable.
You can read more about that in here:
https://stackoverflow.com/a/1471738/7301294
I hope it will help you.
Let me know if you have any other problems and never be afraid to ask.
Good luck!

Drop down list to select a table and an additional drop down list to filter

I want to use 2 drop down lists on the same page, one of them to select the table from the Db and the other to filter the selected table. I think this is very basic but I am new in PHP and SQL. I have no problem to use a submit to filter the table by group but I don't know where assign to $table variable the $_POST['tables'] value.
Here is the relevant part of my code, :
$table=table_name;
if(isset($_POST['tables'])) {
$table=$_POST['tables'];
}
//filtering by group
if(true===isset($_POST['value'])) {
if($_POST['value'] == 'All') {
// query to get all records
$query = "SELECT * FROM $table";
} else {
// filter groups
$value=$_POST['value'];
$query = "SELECT * FROM $table WHERE Grupo='$value'";
}
} else {
// the first time the page is loaded
$query = "SELECT * FROM $table ORDER BY Grupo ASC";
}
$sql = mysqli_query($con,$query);
index.php
<html>
<head>
<script>
function sortResult(str)
{
var e = document.getElementById("firstDrop");
var str1 = e.options[e.selectedIndex].value;
var e = document.getElementById("secondDrop");
var str = e.options[e.selectedIndex].value;
if (str=="")
{
document.getElementById("result").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("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","results.php?q="+str+"&t="+str1,true);
xmlhttp.send();
}
</script>
</head>
<body>
<!--database name-->
<select name="tablename" id="firstDrop">
<option selected='selected' value="yourdatabasename1">DB1</option>
<option value="yourdatabasename2">DB2</option>
</select>
<!--sort by what-->
<select name="sortby" id="secondDrop">
<option selected='selected' value="slno">slno</option>
<option value="name">name</option>
<option value="author">author</option>
</select>
<button id="sub" onclick="sortResult()">CLICK</button>
<br><br>
<div id="result"><b>Results will be listed here.</b></div>
</body>
</html>
results.php
<?php
$q = $_GET['q'];
$t = $_GET['t'];
$con = mysqli_connect('localhost','yourusername','password','database');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM ".$t." ORDER BY ".$q;
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Author</th>
<th>ID</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" .$row['name']. "</td>";
echo "<td>" .$row['author'] ."</td>";
echo "<td>" .$row['slno']. "</td>";
echo "</tr>";
}
echo "</table>";
echo $t;
mysqli_close($con);
?>
modify accordingly.
you have a typo...
if(isset($_POST['tables'])) {
$tabla=$_POST['tables'];
}
change to
if(isset($_POST['tables'])) {
$table=$_POST['tables'];
}
Correct your query syntax--
$query = "SELECT * FROM $table";
to
$query = "SELECT * FROM '".$table."'";
$query = "SELECT * FROM $table WHERE Grupo='$value'";
to
$query = "SELECT * FROM '".$table."' WHERE Grupo='".$value."'";
and
$query = "SELECT * FROM '".$table."' ORDER BY Grupo";
to
$query = "SELECT * FROM '".$table."' ORDER BY Grupo";

Categories