使用PHP和AJAX选择器形式查询MySQL

时间:2018-06-26 18:24:13

标签: php mysql ajax forms undefined-index

我正在编写一些PHP,以从在WAMP服务器上设置的MySQL数据库进行查询。我也正在学习PHP和html javascript,所以两种语言的语法对我来说还是有点陌生​​。

我正在通过服务器运行两个文件front.php和back.php。 front.php包含一个选择器表单,用户可以在其中选择要应用于MySQL的php查询的过滤器。 back.php使用$ _REQUEST接收选择,并在对MySQL的SELECT查询中使用该选择。我已经在下面的front.php中发布了与选择器表单有关的代码。

我在编译时收到“未定义的索引:家庭”错误。 同样,我同时包含了front.php和back.php文件以供参考。

非常感谢您的帮助!

<form method="POST">
<select name="family" onchange="showUser (this.value)">
<option value="empty">Select a Family:</option>
<option value="capacitor">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
</form>

这里是$ _REQUEST调用,该调用在back.php中收到上述选择

$sql="SELECT * FROM testv2 WHERE family='".$_REQUEST['family']."'";
$result = mysqli_query($con,$sql);

FRONT.PHP

<!DOCTYPE html>
<html>
<head>
<script>
function showUser(str) {
  if (str=="") {
    document.getElementById("txtHint").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 (this.readyState==4 && this.status==200) {
      document.getElementById("txtHint").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","back.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="family" onchange="showUser(this.value)">
    <option value="empty">Select a Family:</option>
    <option value="capacitor">capacitor</option>
    <option value="resistor">resistor</option>
    <option value="ferrite bead">ferrite bead</option>
</select>
</form>

<br>
<div id="txtHint"><b>Filter Info to be Displayed Here.</b></div>

</body>
</html>

BACK.PHP

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php

$con = mysqli_connect('localhost','root','kelly188','mysql');
mysqli_select_db($con,"testv2");
$sql="SELECT * FROM testv2 WHERE family='".$_REQUEST['family']."'";
$result = mysqli_query($con,$sql);
return var_dump($sql);

echo "<table>
<tr>
<th>ID</th>
<th>Family</th>
<th>Capacitance</th>
<th>Voltage</th>
<th>Price</th>
</tr>";

while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['family'] . "</td>";
    echo "<td>" . $row['capacitance'] . "</td>";
    echo "<td>" . $row['voltage'] . "</td>";
    echo "<td>" . $row['price'] . "</td>";
    echo "</tr>";
}

echo "</table>";
mysqli_close($con);
?>

</body>
</html>

This is a display of the code before I execute (with the var_dump included)

This is the result of the execution

第一个示例显示了包含var_dump返回的代码 第二张图片是运行代码时在服务器窗口中编译的图片

0 个答案:

没有答案