PHP GET id from articles.php - 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";
}

Related

PHP MYSQL $_GET['ID'] from table on dynamically generated page

I have a few products stored in a table with auto-incremented ID entitled "product_id".
I have managed to create a page that displays a list of the products names as selected from the db and dynamically created links for each one. Let's say I have product apple. When I click on apple it takes me to view_product_details.php?id=9
But when I click apple, the view_product_details.php page tells me
"Notice: Undefined index: product_id in C:\xampp\htdocs\working\product-website-exercise\view_product_details.php on line 16"
<?php
//$result = mysql_query("SELECT * FROM temaproduct.products WHERE ID = '".mysql_real_escape_string($_GET['product_id'])."'");
$id = $_GET['product_id']; //This is line 16
$result = mysqli_query($conn,"SELECT * FROM products WHERE ID = $id");
echo $result['product_description'];
echo "<br>";
var_dump($result);
?>
I have tried with different queries but can't figure it out, please help me establish the connection properly so I can read the other fields from the table on the view_product_details page, based on product_id.
EDIT: Thank you guys, with your help, here is the code that works now, if everybody needs this snippet:
<?php
$id = intval($_GET['id']);
$sql = mysqli_query($conn,"SELECT * FROM products WHERE product_id = ".$id);
if(mysqli_num_rows($sql)){
$product_data = mysqli_fetch_array($sql);
echo "<h2><center>".$product_data['title']."</h2></center>";
}
?>
You are using id as a query string in this URL as:
view_product_details.php?id=9
So, you need to get id as:
$id = $_GET['id']; //This is line 16
Second issue in your code is that, you can not get result from database without using mysqli_fetch_* function.
echo $result['product_description']; // this will return nothing
Your Modified Code:
<?
$id = intval($_GET['id']);
$sql = mysqli_query($conn,"SELECT * FROM products WHERE ID = ".$id);
if(mysqli_num_rows($sql)){
$result = mysqli_fetch_array($sql);
echo $result['product_description'];
}
else{
echo "No record found";
}
?>
Suggestion:
You need to do one more thing, please use intval() function if any one pass string or anything else in the query string than your query will not return an error only return 0 record like:
Example:
view_product_details.php?id=abcdJUNK
Than convert it into 0 as:
$id = intval($_GET['id']);
For Future Visitors:
After debugging, found this error "Unknown Column ID"
so correct query was this as OP mentioned (column name was product_id):
SELECT * FROM hangouts WHERE product_id = 9
You are actually passing id in view_product_details.php?id=9 query params not product_id in the url.
To use product_id you can change the url like view_product_details.php?product_id=9 or you can use $_GET['id']
& replace this line
$id = $_GET['product_id'];
with this
$id = $_GET['id'];
You can use get_defined_vars(http://php.net/manual/en/function.get-defined-vars.php) to check which variables are
available.
Also I suggest you suppress your errors for production & show all errors in developement.
To hide errors in production
ini_set("display_errors", 0);
ini_set("log_errors", 1);
To show errors in developement
error_reporting(E_ALL);
ini_set('display_errors', 1);
According to your code and URL that you provide you are passing value in variable id not in product_id. This is your URL view_product_details.php?id=9 here value is in variable id i.e id=9.
$id = $_GET['id']; //This is line 16
two problems here first your name attribute in html form is different then what you are using in php i changed the php code for that issue and second problem is you are missing to convert the result in to assosiative array and directly calling the product description just read the comments in modified version of code down below.
this is your current code
$id = $_GET['product_id']; //This is line 16
$result = mysqli_query($conn,"SELECT * FROM products WHERE ID = $id");
echo $result['product_description'];
this is how it should be
// this is the solution for first issue
$id = $_GET['id']; //This is line 16
$result = mysqli_query($conn,"SELECT * FROM products WHERE ID = $id");
// this is the solution for second issue
// covert it to associative array
$resultData = mysqli_fetch_assoc($result);
echo $resultData['product_description'];

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?
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

Why is my php/mysql update not accurate?

I have a webpage with a button on it. When the button it clicked it sends a request to a page with this code on it
$userName = "tdscott";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$divID = explode('?', $url);
$id = 0;
$id = explode('#',$divID[1])[1];
$func = $divID[2];
$find = mysqli_fetch_array(mysqli_query($con,"SELECT likes FROM status WHERE id='$id'"))['likes'];
if ($func == "addLike")
{
$promoted = $userName . "-";
mysqli_query($con, "UPDATE status SET promotedBy = CONCAT(promotedBy,'$promoted') WHERE id='$id'");
$find++;
mysqli_query($con,"UPDATE status SET likes = '$find' WHERE id='$id'");
echo $find;
}//end if addLike
elseif($func === "removeLike")
{
echo "ERROR";
}//end if removeLike
elseif ($func === "getLikes")
{
echo $find;
}//end if getLikes
mysqli_close($con);
I left of the database connection information. But for some reason when this is called it produces inaccurate results. For example... Sometimes it will put multiple instances of $promoted in the promotedBy field in my table and sometimes it will update other rows in the table that the id does not equal the current $id. I am wondering if somehow it is getting the $id variable mixed up from when I submitted it with a different value before. Is there a way to reset the variables before I call it each time?
Please note: In the if statement, we are only looking at the addLike portion. I included the other just in case it was causing the problem.
unset($id);
Sorry should have done more research.

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'];
}
}
?>

Categories