我想要实现的是从带有下拉列表的数据库中检索数据。
我可以从数据库中获取name变量,并且可以用表显示所有数据库元素,但是我不知道如何合并这两个。我想单击一个按钮,并显示所选下拉列表项的所有数据库元素/列数据。
这是为下拉列表检索产品名称的代码:
<?php
$mysqli = NEW MySQLi('localhost', 'root', '', 'mydb');
$resultSet = $mysqli->query("SELECT namepro FROM mytable");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>developer mode</title>
</head>
<body>
<select>
<?php
while($rows = $resultSet->fetch_assoc()){
$dropdown = $rows['namepro'];
echo "<option value='$dropdown'>$dropdown</option>";
}
?>
</select>
<button type="button">Click Me!</button>
</body>
</html>
这是显示所有数据库元素的代码:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<table>
<tr>
<th>name</th>
<th>size</th>
</tr>
<?php
$conn=mysqli_connect("localhost","root","","mydb");
$sql = "SELECT namepro, res FROM mytable";
$result = $conn -> query($sql);
if($result->num_rows > 0){
while($row=$result->fetch_assoc()){
echo "<tr><td>". $row["namepro"]. "</td><td>". $row["res"]. "</td></tr>";
}
echo "</table>";
}
else{
echo "0 result";
}
$conn ->close();
?>
</table>
</body>
</html>
我想单击一个按钮,并显示所选下拉列表项的所有数据库元素/列数据。我该如何实现? 谢谢。
答案 0 :(得分:0)
您可以使用jquery & ajax
来实现以上功能。每当按钮为click
时,您的jquery click
函数就会被执行,而select box
的值将为class="select"
}并将其传递到您的php
页面,如下所示:
您的按钮:
<button type="button" class="btn">Click Me!</button>
<div id="show"></div> // here data from respone will be display
jQuery&Ajax :
<script>
$(document).ready(function () {
$(".btn").click(function () {
var value= $(".select").val();//getting value of select box with class="select"
$.ajax({
url: 'yourphppage',
method: 'POST',
data: {value : value},//sending value to yourphppage
success:function(data){
$("#show").html(data);//here response from server will be display
}
});
});
});
</script>
Php代码:
<?php
$value=$_POST['value'];//getting value sent from ajax
$conn=mysqli_connect("localhost","root","","mydb");
$sql = "SELECT namepro, res FROM mytable where namepro='".$value."'";//passing in query
$result = $conn -> query($sql);
if($result->num_rows > 0){
echo "<table>
<tr>
<th>name</th>
<th>size</th>
</tr>";
while($row=$result->fetch_assoc()){
echo "<tr><td>". $row["namepro"]. "</td><td>". $row["res"]. "</td></tr>";
}
echo "</table>";
}
else{
echo "0 result";
}
$conn ->close();
?>
希望这会有所帮助!