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
}
Related
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";
}
This is php code which checks if form(on same page) is posted and gets the result depending upon $_POST array if it is posted or returns all results from data base. this also sets $total variable containing number_of_pages later used for pagination
if(!isset($_POST['search']))
{
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "select SQL_CALC_FOUND_ROWS * from feedbacks order by Date desc limit $id, 10 ";
}
else if (!empty($_POST['from']))
{
$timstmp = strtotime($_POST['from']);
$dt = date("Y-m-d H:i:s", $timstmp);
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM `feedbacks` WHERE `Date` >= \"$dt\" order by Date desc limit $id, 10 ";
}
else if (!empty($_POST['name']))
{
$name = '%'.$_POST['name'].'%';
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM `feedbacks` WHERE `name` LIKE '$name' order by Date desc limit $id, 10 ";
}
$result= mysqli_query($connection, $query);
$r = mysqli_fetch_array(mysqli_query($connection, 'SELECT FOUND_ROWS()'));
$total = ceil($r['FOUND_ROWS()']/10);
$feedbacks = array();
for ($i = 0;$row= mysqli_fetch_assoc($result); $i++)
{
$feedbacks[$i] = new FeedBack($row);
}
?>
These are the html links that are automatically generated depending upon the total number of pages which is calculated depending upon results from data base
<?php
if ($total>1)
{ ?> <div class="pagging">
<?php for( $i=$total; $i>=1; $i--)
{ ?>
<div class="right">
<a id="pagination" href="index.php?id=<?php echo $i; ?>"><?php echo $i; ?></a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<!-- Table -->
On this page I'm implementing filters. User input data in the form and press search so depending upon the $_POST array the different results are loaded and variable $total containing num_of_pages is modified as the 1st block of php code shows now the first page displays 1st 10 results from data base using offset 0 or ofset = IDX10-10 if id is set but problem is that it only works for default results i.e when all results are displayed and filter is not applied but when user searches through a filtered 1st 10 filtered results are displayed but when user clicks the next page it does not work because $_POST is unset which was checked by the php If conditions in above php code. so my question is how can i send $_POST[] along with the id to make it work. Any help would be appreciated. Thanks.
You can't send POST variables through a link. You need to use GET.
Link
//the link will reflect some_page.php?name1=value1&name2=value2...etc
On the PHP side use the $_GET or $_REQUEST variable, instead of $_POST.
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'];
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
I have a members site where users are given up to 7 web page templates to display their products on. Each template has the same field names, differentiated by _1, _2... _7 at the end of each.
For example:
// Template 1 would have the following list of variables
product_name_1
product_descript_1
product_color_1
product_price_1
// Template 2 would have the following list of variables
product_name_2
product_descript_2
product_color_2
product_price_2
// through Template 7
I am able to display any variables for a specific user within a web page, by use of a query string identifying their user_id in the url, ie
http://domain.com/folder/page.php?id=78
I then $_Get any variable by simply identifying it in the PHP file, ie
$product_name_1
$product_descript_1
$product_color_1
$product_price_1
My problem is that the url must identify WHICH template, since each template identifies a specific product, ie _1, _2, ..._7. How do I use a parameter in the url, such as
http://domain.com/folder/page.php?id=78¶meter=_7
...to identify all variables ending with _7, which would appear in the web page? The parameter used in the url would identify the variables to be used in the web page, whether _1, _2, etc.
UPDATE
I have tried the various answers with only partial success, ie "Array_x" is displayed when using any particular variable along with the suggested code. There may be a conflict with the rest of the code I'm using in page.php, as follows:
$db_connection = new mysqli("", "", "");
if ($db_connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
$prop_address=array(
"_1"=>"prop_address_1",
"_2"=>"prop_address_2",
"_3"=>"prop_address_3"
//Through to Temp 7
);
$prop_address{$_GET['parameter']}=$row->prop_address;
echo " $prop_address{$_GET['parameter']} ";
"Array_x" displays (where x=1, 2, 3, etc is used as the parameter in url, ie http://domain.com/page.php?id=72¶meter=1), instead of the actual value held in the database table for $product_name{$_GET['parameter']}. For some reason, the code is not picking up the value of the variable from the database table.
Would it be possible to use arrays so...
$product_name=array(
"1"=>"Product name for template 1",
"2"=>"Product name for template 2"
//Through to Temp 7
);
echo $product_name[$_GET["parameter"]];
You could then do the same for the other variables.
You could fill each array by doing something like:
$row = mysql_fetch_object($query);
$product_name[$_GET['parameter']]=$row->product_name;
echo $product_name[$_GET['parameter']];
I may be missing something...
$_GET['parameter'] = '_2';
$product_name{$_GET['parameter']} = 'string';
echo $product_name_2; // string
or
$_GET['parameter'] = '_2';
$var = 'product_name'.$_GET['parameter'];
$$var = 'string';
echo $product_name_2; // string
Personally, I would use array's for this type of behavior.
Update:
Although the above works and tested ok, it is a lot more work than anyone would probably desired.
In lieu of simplicity, I would suggest the approach via array's.
$templates = array(2 => array(
'product_name' => "value",
'product_descript' => "value",
'product_color' => "value",
'product_price' => "value",
);
foreach($templates[substr($_GET['parameter'],1)] as $var => $val){
$variable = $var.$_GET['parameter'];
$$variable = $val;
}
The above is backwards compatible, it uses substr to remove the leading _ from your parameter.
I couldn't get any of the answers given to work. I found an example given by a user for php variable variables in the PHP manual here and found it to work. I incorporated it into my code as follows:
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
for( $i = 1; $i < 8; $i++ )
{
$product_name[$_GET['parameter']] = "product_name_" . $i;
$product_descript[$_GET['parameter']] = "product_descript_" . $i;
$product_color[$_GET['parameter']] = "product_color_" . $i;
$product_price[$_GET['parameter']] = "product_price_" . $i;
}
${$product_name[1]} = "$row->product_name_1";
${$product_name[2]} = "$row->product_name_2";
${$product_name[3]} = "$row->product_name_3";
${$product_name[4]} = "$row->product_name_4";
${$product_name[5]} = "$row->product_name_5";
${$product_name[6]} = "$row->product_name_6";
${$product_name[7]} = "$row->product_name_7";
// List 7 variables and values for each field name
echo "${$prop_name[$_GET['par']]}";
The only problem is that mysql injection is possible with this code. If anyone could suggest a solution, I would greatly appreciate it.