繁体   English   中英

HTML 表单数据未发布以在 SQL 查询中使用

[英]HTML form data not being posted to use in SQL query

this should be simple but I have lost my way simple form on HTML page - select Men, Women or Junior then send that that value to a php page to perform SQL query and find all the Men, Women or Juniors using the variable "$trigen " 使用 AJAX 在 HTML 页面上显示结果

如果我手动设置 $trigen 它可以工作,但当我选择此代码中列出的表单中的选项时则不行:-

我的 HTML:-

<!DOCTYPE html>
<html>

<div class="entry-content">
        

<form action="/getcustomer.php" method="POST">
  <label for="trigen">Choose a gender:</label>
  <select id="trigen" name="trigen">
    <option value="Men">Men</option>
    <option value="Women">Women</option>
    <option value="Junior">Junior</option>
  </select>


<button class="btn btn-primary text-center btn-block btn-flat" style="h2; margin: 20px; color:black;  " name="trilookup" type="submit" onclick="showResults()"> Search</button>

 
</form>

   </div>
   
<div id="results">Results go here if it works....</div>


<script>



function showResults(str) {
  
  var xhttp;
  if (str == "") {
    document.getElementById("results").innerHTML = "";
    return;
  }
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("results").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "getcustomer.php?q="+str, true);
  xhttp.send();
}
</script>

然后是“getcustomer.php”中的我的 php 代码

<?php  


    //connect to the database
    
  $conn=mysqli_connect('localhost','wetsuder_user1','user123','wetsuder_finder');
  if($conn){
      
  }
  else{
     echo  "Sorry there is a connection error".mysqli_connect_error();
  }

                 
$trigen=$_POST['trigen'];
    
 
 //this is the search
 
$sql = "SELECT id, Gender, Wetsuit FROM wp_wetsuitdata WHERE Gender = '$trigen'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    
  echo "<table><tr><th>ID</th><th>Name</th></tr>";
  
  
  // output data of each row
  
  while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["id"]."</td><td>".$row["Gender"]." ".$row["Wetsuit"]."</td></tr>";
  }
  echo "</table>";
} else {
  echo "0 results";
}
$conn->close();
?>

您的button导致表单提交。 只需将preventDefault()添加为showResults function 的第一行,它将阻止表单自然提交。 您正在通过 ajax 处理表单提交。 出于同样的原因,您也不需要在<form标记上使用操作或方法。 另一种阻止表单提交的方法是这样的: <form onsubmit="return false"

此外,更改您的 function 以找到您要发送的值,因为您实际上并没有通过 function 调用str传递该值

function showResults() {
  preventDefault(); // prevents form submission
  // get the value
  let str = document.getElementById('trigen').value;
  // check to make sure it's there...
  if (!str) return alert("Please select an option...");
  var xhttp;
  ......

您通过 GET 发送数据(当您在 URL 上使用?q=val 时,数据正在通过 GET 发送。因此,您可以在 PHP 中接收它:

$trigen=$_GET['q'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM