PHP Search Results - Retrieve Data based on ID in URL - php

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?

Typically this is done by passing an id in a parameter via GET. So links on the listing page may look like this:
echo '' . $link_text . '';
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

Related

PHP highlight selected item

Just like the image above, when the user clicks one of the list on the right side, it highlights the selected one.
$result = mysqli_query($con, "SELECT * FROM contacts") or die(mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$company = $row['eyo_company_name'];
$id = $row['con_id'];
$editLinks .= "\n\t$company<br>";
}
this is how I brought the list out from the database. Would there be any way I could add a class or add b tag on selected one only ?
If I understand correctly, you are trying to highlight one of the links output by PHP. To do so you will need to know which one to highlight.
If you have a GET variable set to the current contact ID, you could do something like this:
while($row = mysqli_fetch_array($result)){
$company = $row['eyo_company_name'];
$id = $row['con_id'];
//let's check if we've pre-selected a company
// and if so, is this the company we selected?
if (true === array_key_exists('CURRENT_COMPANY_ID', $_GET) && $id === $_GET['CURRENT_COMPANY_ID']) {
//we did select this company for this PHP request
// let's make the HTML output custom to highlight the selected company
$editLinks .= "\n\t<strong>$company</strong><br>";
} else {
$editLinks .= "\n\t$company<br>";
}
}
This example expects that your request to the PHP script generating your list of links will include CURRENT_COMPANY_ID=<ID HERE> in the URL.
For example, if the URL for the request that generates your list of links looks like this:
/getMySuperAwesomeList.php
It would need to look like this:
/getMySuperAwesomeList.php?CURRENT_COMPANY_ID=123
Where 123 matches the con_id of the record you want to highlight.
I chose to use array_key_exists() to make sure that the request actually included the CURRENT_COMPANY_ID data in the URL. Here is documentation for that function: https://www.php.net/array_key_exists

PHP GET id from articles.php

I have an Articles.php page and a Single.php page. Articles.php runs a foreach loop listing all of the articles. The href anchor for each article is:
<a href="single.php?id=<?php echo $article['id'];
When the article link is click the URL becomes:
example.com/single.php?id=*ID*
I am having trouble grabbing that article ID on the single page to show the MySQL row specific to that id. The following was suggested:
$id = filter_var($_GET['id'] ?? false, FILTER_VALIDATE_INT);
if($id !== false){
//show the article, i.e. select * from .... where id = id ...
echo "WORKING";
}else{
//show the error like 404
echo "ERROR";
}
Should this be:
$id = $_GET($article['id'])
I am having trouble making this work.
Send value to another page using..
Link //missing php close tag here
Then get it using
$id = $_GET['id'];
ok lets try this.
on page 1 => article.php
# we assume
database query here
$query = mysqli_query(//query here);
// we then use a while loop
while($q = $query->fetch_array())
{
echo ''.$q['article_name'].'';
}
ok on page single.php
# we now have example.com/single.php?id=1 eg.
// there are many ways to grab the id
# option 1
// inside single.php
// method 1
$article_id = isset($_GET['id']) ? (int) $_GET['id'] : "";
// method 2
$article_id2 = "";
if(isset($_GET['id']))
{
$article_id2 = $_GET['id'];
}
// now you have the value from the GET method within your local variable scope
// so choose any of the method above
// both works
hope this helps?
As Hek mat said you missed the Clossing tags:
Link
But you your code is also not correct $_GET['id'] is giving always a string "1" not a int 1 and if the id is not set this would cause an error.
So try this:
if(isset($_GET['id']) && intval($_GET['id']) > 0){
$id = intval($_GET['id']); // now work with $id its an int now
//show the article, i.e. select * from .... where id = id ...
echo "WORKING";
}else{
//show the error like 404
echo "ERROR";
}

Issues with dynamically generated web pages

Please I need your help with my script. I'm puting a link to old news articles in a sidebar and making it clickable. The page it's coming from (header.php) has the GET id in the URL, so the page receiving it also checks for the value of the GET. It displays fine when I click the old news article in the sidebar.
The problem I'm having is that, whenever I want to view the current article on the the About.php page I get Undefined Index id
Please how can I solve this issue, so that my script works well for displaying old articles and also the current news article.
Thanks
about.php
<?php
$id = $_GET['id'];
$past = mysql_query( "SELECT * FROM about WHERE about_id = '".$id."'") or die(mysql_error());
$row = mysql_fetch_array($past);
echo "<h2>";
echo $row1['about_head'];
echo "</h2>";
echo "<p>";
echo $row1['about_content'];
echo "</p>";
?>
Header
<?php
$past = mysql_query("SELECT * FROM about") or die(mysql_error());
while($row = mysql_fetch_array($past))
echo " $row[about_head].<br/>";
?>
When you have this code:
$id = $_GET['id'];
you are retriving an item called "id" from the array called $_GET (which holds all GET parameters). However when this parameter "id" is not present, PHP emits a warning. To get rid of it, replace the line with:
$id = "";
if (isset($_GET["id"])) $id = $_GET["id"];
or shortly:
$id = isset($_GET["id"]) ? $_GET["id"] : "";
which first asks whether the parameter is present, and if it's not, gives an empty string. If you expect the $id variable to be an integer, you might instead want to use zero instead of an empty string:
$id = isset($_GET["id"]) ? (int)$_GET["id"] : 0;
this also casts the passed parameter to "int", so you have a guarantee that it is not a string (possibly containing malicious data).
Something like this should work:
if( array_key_exists( 'id', $_GET ) )
{
//do your code in here
}
else
{
//fallback to scenario in which $_GET['id'] isn't set in the url
}

Array_Push not adding to end of array, it is replacing the whole array

I have tried to create a small 'bookmarking' feature for my website. Users are able to click on the ".bookmarkButton" which will execute the following script:
<!--Add To Bookmarks-->
$(".bookmarkButton").click(function() {
var pid=$(this).closest('div').attr('id');
$('#noBookmark').hide();
$.post('bookmarks/addBookmark.php', 'rid=' + pid, function (addBookmark) {
$("#bookmarkResults").add(addBookmark);
});
});
Here is the code for "addBookmark.php":
<?php
session_start();
if (isset($_SESSION['ridArray']) && count($_SESSION['ridArray'] > 0)){
addBookmark();
} else if (isset($_POST['rid']) && !isset($_SESSION['ridArray'])) {
$_SESSION['ridArray'] = array();
addBookmark();
}
function addBookmark() {
if (is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray']) && isset( $_POST['rid']) ) {
array_push($_SESSION['ridArray'], $_POST['rid']); //push the id value from post to the session array
//$_SESSION['ridArrayClean'] = array_unique($_SESSION['ridArray']); //remove duplicates
print_r($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example WHERE id = $x")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}}}
?>
The variable $_SESSION['ridArray'] holds the array with all the id's that have been accumulated.
My problem is that this script works only when one item is bookmarked. When there is more than one product bookmarked, I only get the product name that was last bookmarked and not every thing that I've bookmarked.
So for example instead of getting multiple product id's after clicking the bookmarkButton class like this: 0,1,2,3 in the array. I only get the one that was clicked last i.e. 6.
I've been looking into this for a while now and I can't seem to see what I'm doing wrong.
The script only echos the productnames, if you posted a "rid".
Also you could write the if like this:
if (isset($_SESSION['ridArray'], $_POST['rid']) && is_array($_SESSION['ridArray'])) {
Checking isset() first. Also you could additionally check for
... && count($_SESSION['ridArray'] > 0)
I do not think that your session starts automatically (is it possible to set its autostart in php.ini, but it does not by default), so
<?php
session_start();
Other thoughts:
SELECT * FROM example WHERE id = $x
Have you ever heard about SQL Injection?
ps: no need in secondary check (they are checked before) and from the first condition follows the second one
is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray'])
I would write it as
<?php
session_start();
if (isset($_POST['rid'])) {
addBookmark(intval($_POST['rid']));
}
function addBookmark($rid) {
$_SESSION['ridArray'][] = $rid;
$_SESSION['ridArray'] = array_unique($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
$result = mysql_query("SELECT * FROM example WHERE id = '$x'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}
}
?>

How can I do a sort and search using both GET and POST variables?

I am currently using column header's as links that when clicked will sort the results by the column name by adding a get variable to the url. Here is an example:
<a href="
<?php
// Sorts by order id. If already sorted by order id, then it will change the link to sort descending
if(!isset($_GET['sortby']) || $_GET['sortby'] != 'order_id'){
echo $_SERVER['SCRIPT_NAME'] . '?sortby=order_id'; //example: tracker.php?sortby=order_id
} elseif(isset($_GET['sortby']) || $_GET['sortby'] == 'order_id'){
echo $_SERVER['SCRIPT_NAME'] . '?sortby=order_id_desc'; //example: tracker.php?sortby=order_id_desc
}?>
">Order ID</a>
I also have a form where users can enter pick a category from a selectbox and then enter a searchterm. I am using if statements and switch statements to check if the $_GET['sortby'] variable and the $_POST['search_submit'] variable is set and if so, to run a certain sql statement based on the value of the GET variable.
There are 4 different scenarios.
1. Default: If neither sort nor search is set. This one works fine:
if(!isset($_GET['sortby']) && !isset($_POST['search_submit'])){ //Default, If no sort or search is set
$sql = 'SELECT *
FROM orders
ORDER BY order_id DESC';
}
2. If the search is set but the sort is not. This one works fine:
if(isset($_POST['search_submit'])) {
$search_string = ' WHERE ' . $_POST['searchby'] . '= "' . $_POST['search_input'] . '" ';
}
if(!isset($_GET['sortby']) && isset($_POST['search_submit']) ){ //If the search is set but no sort
$sql = "SELECT *
FROM orders"
. $search_string .
"ORDER BY order_id DESC";
}
3. If the sort is set, but the search is not. This one works fine:
if(isset($_GET['sortby']) && !isset($_POST['search_submit'])) { //If the sort is set but no search
switch ($_GET['sortby']) {
case "order_id":
$sql = "SELECT *
FROM orders
ORDER BY order_id ASC";
break;
case "order_id_desc":
$sql = "SELECT *
FROM orders
ORDER BY order_id DESC";
break;
}
}
4. If the search AND sort is set. All 3 of the above if statements work, but the last one is giving me problems.
if(isset($_GET['sortby']) && isset($_POST['search_submit'])) { //If the sort AND search is set
switch ($_GET['sortby']) {
case "order_id":
$sql = "SELECT *
FROM orders"
. $search_string .
"ORDER BY order_id ASC";
break;
case "order_id_desc":
$sql = "SELECT *
FROM orders"
. $search_string .
"ORDER BY order_id DESC";
break;
}
}
What happens is that you can search, but as soon as you click on one of the column headers and it reloads the page with the new GET variable, it will get rid of the current POST variable, thereby showing all results again. I tried to load the current POST variable into a session after the $_POST['search_submit'] isset and then make the last if statement check to see if the session variable is set, but what happens then is that the session is always set and if i try to go back to the homepage, it will keep those search results.
Perhaps I need to destroy the session somewhere? Perhaps there is an overall better approach I could be taking to combining sort and search features?
I would recommend changing the search form from a method="POST" to method="GET" and use just GET for all your requests. If you cannot change your POST requests, you are going to need to POST each request (including sorting), which will require javascript attached to your sort links.
The benefit to using GET is that your users can bookmark specific searches since all the data would be contained in the Query string.
EDIT: Retaining the search strings in subsequent requests:
I would abstract out your sorting code to something like this:
<?php
function write_sortable_header_link( $column_id, $column_name ){
if( ( isset($_GET['sortby']) && $_GET['sortby'] != $column_id ) || !isset($_GET['sortby']) )
$query = "?sortby=$column_id";
else
$query = '?sortby='.$column_id.'_desc';
if( isset($_GET['searchsubmit']) ){
$query .= '&searchsubmit=1';
$query .= '&searchby=' . urlencode( isset($_GET['searchby']) ? $_GET['searchby'] : '' );
$query .= '&search_input=' . urlencode( isset($_GET['search_input']) ? $_GET['search_input'] : '' );
}
$href = $_SERVER['SCRIPT_NAME'] . $query;
echo "<a href='$href'>$column_name</a>";
}
?>
You would then call it like this:
<?php write_sortable_header_link( 'order_id', 'Order Id' ); ?>
It would make sure your sorting URL's contain the correct query string arguments for persistence.
Try to use $_GET only, involving $_POST seems unnecessary.
Not an answer to your question, but just my 0.2
In your situation I usually do the sorting client side in the web browser using javascript. It prevents essentially the same query being run over and over again with only different ORDER BY parameters.
With jquery there are even some very nice plugins that make it pretty easy.
example: http://tablesorter.com/docs/
This is the code I ended up using to make the link rewrite with the sort and search get variables as suggested by dcneiner. I took out the urlencode, the switched & to the '&' sign and made the inline if statement read as just the get variable, since the only way those get variables can be set is if the search_submit is set since they're part of the same form. I also added the '{' and '}' back into the if and else statements. I'm guessing you're using a slightly different way of doing PHP? Do you see anything wrong or unsecure about the changes I made? I wasn't too sure why you did it your way. But thanks again.
function write_sortable_header_link( $column_id, $column_name ){ //Function that creates a link with the search query if needed
if( ($_GET['sortby'] != $column_id) || !isset($_GET['sortby']) ) { //If the GET variable is not the column id of this button or if the GET sortby variable has not been set
$query = "?sortby=$column_id"; //then add this to the end of the url
} else {
$query = '?sortby='.$column_id.'_desc'; //otherwise if the GET variable is the column id of this button, then add the descending code to the end of the variable
}
if(isset($_GET['search_submit']) ){ //If the GET variable search_submit is in the url
$query .= '&search_submit=1'; //then add this to the end of the url string
$query .= '&searchby=' . $_GET['searchby']; //add whatever is currently in the GET searchby to the end of the url string
$query .= '&search_input=' . $_GET['search_input']; //add whatever is currently in the GET search_input to the end of the url string
}
$href = $_SERVER['SCRIPT_NAME'] . $query; //this is the href part of the link
echo "<a href='$href'>$column_name</a>"; //this creates the actual link
}

Categories