【问题标题】:how to use multiple HTML text inputs to make an SQL search query如何使用多个 HTML 文本输入进行 SQL 搜索查询
【发布时间】:2014-08-29 19:20:36
【问题描述】:

我有一个包含多个 html 文本输入的表单,我想使用这些输入的值来进行一个搜索查询(例如,我希望它看起来像这样 results.php?input=value1+value2+value3)我试过了,但是我还没有设法得到一个查询来自 3 个输入字段的所有值的查询。

$input = $_GET['input']; //this is for the text input - ignore
$topic = $_GET['topic']; // the first select box value which works well
$location = $_GET['location']; //the second select box value which isn't being inserted into the query
$combined = $input . $topic . $location;
$terms = explode(" ", $combined);
$query = "SELECT * FROM search WHERE input='$input' AND topic ='$topic' AND location='$location' ";'

【问题讨论】:

  • 用一个输入字段编写查询很容易。添加更多更容易:添加更多表单字段,将其数据导入 PHP,然后在查询中使用 and 和/或 or 将 where 子句中的各个字段子句链接在一起。但这取决于你。我们不是来教你什么是基本的 PHP 和 SQL。
  • 请向我们展示您尝试过的代码。如果您不向我们展示您已经完成的工作并具体告诉我们您遇到的问题,我们将无能为力。
  • $_GET['location'] 的值是多少?
  • 请打印所有变量的值。您的代码也容易受到SQL injection attack 的攻击。你应该使用MySQLi。

标签: php html mysql sql


【解决方案1】:

您可以按照您展示的方式进行操作,但您应该使用内置的 PHP 函数通过准备好的语句转义输入,例如使用 mysqli 的 bind_param:

$db = new mysqli(*your database connection information here*);
$input = $_GET['input']; //this is for the text input - ignore
$topic = $_GET['topic']; // the first select box value which works well
$location = $_GET['location']; //the second select box value which isn't being inserted into the query
$combined = $input . $topic . $location;
$terms = explode(" ", $combined);
$stmt = $db->prepare("SELECT * FROM search WHERE input = ? AND topic = ? AND location = ?");
$stmt->bind_param("sss", $input, $topic, $location);
$stmt->execute();
$stmt->close();

至于获取你想要的 URL 的表单:

<form action="results.php" method="GET">
  <input type="text" name="input">
  <input type="text" name="topic">
  <input type="text" name="location">
</form>

操作设置为results.php 脚本,方法设置为GET,以便将表单输入放入URL。

【讨论】:

  • 非常感谢你解释得很好!我真的很感谢你花时间写这一切。我刚刚在我的代码中实现了这个并得到了这个错误:致命错误:调用/customers/c/8/c/adamallard.info/httpd.www/ta/results中的非对象上的成员函数bind_param()。第 150 行的 php 第 150 行是 '$stmt->bind_param("sss", $input, $topic, $location); '
  • 如果$db-&gt;prepare 部分返回false,通常会发生这种情况。如果它返回 false,请检查您的表名和列名以确保它们存在并且在 select 语句中拼写正确。这通常是最常见的罪魁祸首。
  • 不想再打扰你了,但现在我收到了这个错误:'Call to a member function bind_param() on a non-object'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多