【发布时间】:2020-06-28 12:00:58
【问题描述】:
我尝试对其进行编码。我仍然陷入困境。主要目标是如果用户从 mysqli 数据库中选择值选择它并将值发送到其他页面。我知道人们推荐 AJAX 使用它。我尝试使用它。还是行不通。我会在下面放详细代码。
主页代码(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<a href="database1.php">click </a>
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
作为警告框,我正在获取它的值,但第二页出现键值不存在的错误。这里是第二页(database1.php)-
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
那么问题出在哪里?
更新答案
感谢@swati,她提到使用表单标签而不是 AJAX(我知道它的简单答案),顺便感谢您的回答。 :)
更新的代码已满 -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
第二页(database1.php)变化不大 -
$database=$_GET['tables'];
【问题讨论】:
-
你有一个错误。
mysqli_error()需要一个参数。请考虑打开错误模式。 How to get the error message in MySQLi? -
@Dharman 它不需要关心数据库。一切都完美的mysqli。效果很好。
-
我知道它对你很有效,但你看不到错误,这正是我想警告你这个问题的原因。