我想根据下拉列表中的选项从数据库中选择数据,例如当我选择A时,它从表A中选择数据但是当我选择B时,它应该从表中选择数据。
这是我的下拉列表代码:
<div class="form-group"><label class="col-sm-4 control-label">Project / پروژه</label>
<div class="col-sm-4"><select class="form-control m-b" name="account">
<option></option>
<option>Tawanmandi</option>
<option>option 3</option>
<option>option 4</option>
</select>
</div>
这是我的SQL查询
<?php
$mysqli = new mysqli( 'localhost', 'user', 'pass', 'mis_db' );
if (mysqli_connect_error()) {
echo mysqli_connect_error();
exit();
}
if (isset($_POST['submit']))
//Table A and B should switch when i select the Option A or B from dropdownlist
{
$query = 'SELECT * FROM //A or B table';
$data = mysqli_query($mysqli, $query) ;
if (!$data) {
echo("Error description: " . mysqli_error($mysqli));
} else {
while ($row = mysqli_fetch_array($data)) {
echo "<tr>
<td>" . $row['NOTW'] . "</td>
<td>" . $row['Aim'] . "</td>
<td>" . $row['date'] . "</td>
<td>" . $row['Funded'] . "</td>
<td>" . $row['Male'] . "</td>
<td>" . $row['Female'] . "</td>
<td>" . $row['Disabled'] . "</td>
<td>" . $row['Total'] . "</td>
<td>" . $row['Comments'] . "</td>
</tr>";
}
}
}
?>
抱歉我的英语不好:(
答案 0 :(得分:0)
您可以根据所选的选项编写不同的查询。像这样 -
$query = '';
if($_POST['account']=='A') {
$query = 'SELECT * FROM tableA';
} else if($_POST['account']=='B') {
$query = 'SELECT * FROM tableB';
}
答案 1 :(得分:0)
switch ($_POST['account']) {
case 'Option A':
$query = 'SELECT * FROM TableA';
break;
case 'Option B':
$query = 'SELECT * FROM TableB';
break;
default:
exit('unexpected input');
break;
}
您可以像这样定义您的查询。必须调整除A或B之外的其他值的实际值,查询和行为。
我认为你应该更喜欢switch
而不是if
,因为只需添加cases
就可以更轻松地扩展它。
答案 2 :(得分:0)
您可以使用jquery满足要求。 HTML代码是:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
function getData(){
var tableName = $( "#myselect" ).val();
if(tableName!=''){
$.ajax({
url:'database.php',
data:{tableName:tableName},
success:function(data){
$("#result").html(data);
}
});
}
}
</script>
</head>
<body>
<div class="form-group"><label class="col-sm-4 control-label">Project</label>
<div class="col-sm-4"><select id ="myselect" class="form-control m-b" name="account" onchange="getData();">
<option></option>
<option>table1</option>
<option>relation</option>
<option>question</option>
</select>
</div>
<div id="result"></div>
</body>
</html>
Database.php代码是
$tableName = $_GET['tableName'];// die;
if($tableName!='') {
$con = mysql_connect("localhost","root","");
if($con) {
$db = mysql_select_db('test');
if($db) {
$query = mysql_query("Select * from ".$tableName) or die(mysql_error());
$row = mysql_fetch_array($query);
echo $row['id'];
}
}
}