初学者 PHP / SQL / AJAX - 当参数传递给服务器端脚本时查询不起作用


Beginner PHP / SQL / AJAX - Query not working when parameter passed to server side script

我开始学习PHP + AJAX + SQL。我似乎无法破解我遇到的语法问题。我正在网络中的服务器上运行最新的 WAMP 版本作为测试环境。

我的索引中有以下脚本。PHP(从 W3Schools.com):

<script>
$(document).ready(function() {
    $('#submit').click(function() {
        str = document.getElementById("cn").value;
        if (str=="")
          {
          document.getElementById("txtHint").innerHTML="No name typed, returning all rows ";
          str="all";
          }; 
        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 (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
            }
          };
        xmlhttp.open("GET","getcustomer.php?q="+str,true);
        xmlhttp.send();
    });
});
</script>

然后我有一个名为GETCUSTOMER的服务器端脚本。PHP,它(部分)包含以下内容:

<?php
$q = $_GET['q'];
echo "The variable contains = ".$q;   **<--- this shows me on the browser the correct variable value is passed to the server side script**
$con = mysqli_connect('localhost','phpuser','abc123','learnphp');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  };
mysqli_select_db($con,"PHP_AJAX_Demo");
if ($q == "all") {
    $sql="SELECT * FROM customers";
} else {
    $sql="SELECT * FROM customers WHERE 'Company' = '" . $q . "'";
};
$result = mysqli_query($con,$sql);

当我的主表单以 COMPANY 的"空白"值提交时,它工作正常,因为执行"str=all"并将 CUSTOMERS 表中的所有行返回给浏览器。当我使用值(存在于表中)提交它时,我没有返回任何行。我也没有收到任何错误。

语法来自 W3,适用于他们的演示。我错过了什么?提前感谢!

当使用单引号指示字符串值的开头和结尾时,您将单引号放在列名周围。请改用反引号。改变:

$sql="SELECT * FROM customers WHERE 'Company' = '" . $q . "'";

$sql="SELECT * FROM `customers` WHERE `Company` = '" . $q . "'";

请注意,此脚本对 SQL 注入开放,您应该使用预准备语句。