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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With