user2379090
user2379090

Reputation: 123

how to use multiple HTML text inputs to make an SQL search query

I have a form that contains multiple html text inputs, and I'd like to use the values of these inputs to make one search query (for example I want it to look like this results.php?input=value1+value2+value3) I've tried, however I haven't managed to get one that queries with all the values from the 3 input fields.

$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' ";'

Upvotes: 0

Views: 2617

Answers (1)

Samsquanch
Samsquanch

Reputation: 9146

You can do it the way you've shown, but you should really be using built in PHP functions for escaping input via prepared statements, for example with mysqli's 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();

As for the form to get the URL you're wanting:

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

The action is set to your results.php script, and the method is set to GET in order to have the form inputs put in the URL.

Upvotes: 1

Related Questions