我想在同一页面上使用2个下拉列表,其中一个用于从Db中选择表格,另一个用于过滤选定的表格。我认为这是非常基本的,但我是PHP和SQL的新手。我可以使用提交按组过滤表格,但我不知道将$table
变量分配到$_POST['tables']
值的位置。
以下是我的代码的相关部分:
$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);
答案 0 :(得分:1)
的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);
?>
相应修改。
答案 1 :(得分:0)
你有一个错字......
if(isset($_POST['tables'])) {
$tabla=$_POST['tables'];
}
更改为
if(isset($_POST['tables'])) {
$table=$_POST['tables'];
}
答案 2 :(得分:-1)
更正您的查询语法 -
$query = "SELECT * FROM $table";
到
$query = "SELECT * FROM '".$table."'";
$query = "SELECT * FROM $table WHERE Grupo='$value'";
到
$query = "SELECT * FROM '".$table."' WHERE Grupo='".$value."'";
和
$query = "SELECT * FROM '".$table."' ORDER BY Grupo";
到
$query = "SELECT * FROM '".$table."' ORDER BY Grupo";