Mike E
Mike E

Reputation: 153

PHP Search Results - Retrieve Data based on ID in URL

I have a PHP search function which retrieves items from my database and displays them on a search results page. When clicking on a search result, it currently takes you to a separate html page (for each search item) which contains further details about the item.

I would like to link each search result to one PHP page which gets the item ID from the URL and then retrieves and displays the relevant data from the database.

Below is the PHP code from the page which displays the search results, but I am not sure where to edit this, to link each item to the dynamic PHP page and then retrieve the ID from the URL on the dynamic PHP page?

<?php
if (!empty($data)){
foreach ($data as $item){
echo '<div class="item">';
if (strlen($item['item_image']) > 10){
if(strlen($item['item_link']) > 10){
echo '<a href="'.$item['item_link'].'">';
}
else {
echo '<div class="fail ">No Results Found;
}
?>

Edit:

I have used the below code on the detail_page.php

<?php $db =
mysql_connect("","","") or die("Database     Error");
mysql_select_db("items",$db); $id =     $_GET['id']; $id =     mysql_real_escape_string($id); $query =     "SELECT * FROM `items-one` WHERE `id`='"     . $id . "'"; $result = mysql_query($query); 

But now need to call all of the row fields from the ID in the database and then add them at various points throughout the page?

Upvotes: 0

Views: 1489

Answers (1)

Mike Brant
Mike Brant

Reputation: 71422

Typically this is done by passing an id in a parameter via GET. So links on the listing page may look like this:

echo '<a href="/path/to/detail_page.php?id=' . $id . '">' . $link_text . '</a>';

Here $id and $link_text maybe be populated in loop or whatever.

On /path/to/detail_page.php page you would have some code like this:

// validate that there is an integer-like value passed in `$_GET['id']`
// if so, set value to $id
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
// see results of filtering and behave accordingly
if (is_null($id)) {
    // $_GET['id'] was not set
    // do something and exit
} else if (false === $id) {
    // the value at $_GET['id'] didn't pass validation filter
    // do something and exit
}

// $id has a good integer value
// note you would probably need additional validation checks on the id value
// i.e. make sure value is not negative or 0
// you may want to cast $id to int to make these checks
// for example:
$id = int($id);
if ($id < 1) {
    // bad $id value
    // do something and exit
}
// read data from DB and display it

Upvotes: 1

Related Questions