I need help! for the life of me, I can't figure out what I am doing wrong... I'm trying to build a simple search script that returns some results from a mysql database, and from those results i want to be able to click each individual one and pass it through to a new page, lets say results.php, where the details of that result is loaded, similar to an ecommerce site i suppose, where a result of products are displayed, and on clicking one, that product and its additional details are loaded in a new page. I know i need to pass the id into the url, but the problem i keep getting is that it is only passing the last id from the search result into the url... however collects all the correct id's in the search results...?
I am extremely new to php pdo etc. I have tried to find a solution online, spent days looking, but I keep either getting the same result, or I get and error, which would suggest I didnt do it right... Anyway, this is what I have so far:
<?php
require('inc/connect/config.php');
$output = "";
if(!isset($_POST['search'])) {
$output = "";
}
if(isset($_POST['search'])) {
$search_query = $_POST['search'];
$search_query = preg_replace("#[^0-9a-z]#i", "", $search_query);
try {
$query = $db->prepare('SELECT * FROM clients WHERE name LIKE "%' . $search_query . '%" OR town LIKE "%' . $search_query . '%"');
$query->execute();
while($r = $query->fetch(PDO::FETCH_ASSOC)) {
$bname = $r['name'];
$btown = $r['town'];
$id = $r['id'];
$output .= $bname . '<br>' . $btown . '<br>' . $id . '<br><br>';
}
if($query->rowCount() < 1) {
$output = "no results found";
}
} catch (PDOException $e) {
echo "failed search";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>search</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div style="padding: 20%; text-align: center;">
<h3>search</h3>
<p>or search by <a href="categories.php">category</a></p><br>
<form method="post" action="search-test.php">
<label><3 </label><input type="text" name="search" id="search" placeholder="search by brand or town..." style="width: 40%;"><br><br>
<input type="submit" value="search">
</form>
<br>
<a href="results.php?id=<?php echo $id; ?>"><?php echo $output; ?></a>
</div>
</body>
</html>
When performing a search, the results returned are like this:
business1
town
1
business2
town
2
business3
town
3
but for the url link through to the results.php page, it assigns each result with the id of 3... it only ever passes the last id in the results set to the url... what am i doing wrong? please help!!
thanks in advance