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'];
Related
I am trying to code it so users can type in their -- or others -- usernames which will be converted in their UUID then returns that user's stats from my MySql databse.
The code I attempted this with is
$username = $_POST['searchbox'];
$json = file_get_contents("https://api.mojang.com/users/profiles/minecraft/".$username);
$obj = json_decode($json);
$id = $obj->id;
$rank = Database::query("SELECT * FROM playerdata WHERE uuid=:uuid", array(':uuid'=>"".$id))[0]['rank'];
echo 'Showing results for '.$_POST['searchbox'].' '.$id.' Rank: '.$rank;
Except when I run this code it outputs:
"Showing results for kingbluesapphire 0d8d246d11c54cbbb197c6bc8ba01ee2 Rank:"
I know it's not a problem with the connection to the database because other queries are working
My goal right now is to get the field in the MySql Database thats called rank and I would like to display their rank.
Given the discussion in the comments, either you have to find out what is removing the dashes which I highly recomend to or change your query to:
$rank = Database::query("SELECT *
FROM playerdata
WHERE replace(uuid, '-','')=:uuid",
array(':uuid'=>"".$id))[0]['rank'];
Databases need to be given the exact value you are looking for, any different character in a equals operation will not give you any data.
It's more like:
<?php
if(isset($_POST['searchbox']){
$sb = $_POST['searchbox']);
$json = json_decode(file_get_contents("https://api.mojang.com/users/profiles/minecraft/$sb"));
if($queryRes = $connection->query("SELECT * FROM playerdata WHERE uuid={$json->id}")){
if($queryRes->num_rows){
$o = $queryRes->fetch_object(); // guessing there's only one row or you would put this in a while loop
echo "Showing results for $sb {$o->uuid} Rank:{$o->rank}";
}
}
else{
die($connection->connect_error);
}
}
?>
I'm assuming uuid is a number. Do tell.
I have these two block of codes on one page in different parts of the page any time I try to use $product_id variable on the other segment of the code it is not recongnised. Take a look.
<?php
$cart_table = mysql_query("select * from order_details where memberID='$ses_id' and status='Delivered' and addon_status=''") or die(mysql_error());
$cart_count = mysql_num_rows($cart_table);
while ($cart_row = mysql_fetch_array($cart_table)) {
$order_id = $cart_row['orderid'];
$status = $cart_row['status'];
$product_id = $cart_row['productID'];
$orderdate = $cart_row['ordertime'];
//Query Product table
$product_query = mysql_query("select * from tb_products where productID='$product_id'") or die(mysql_error());
$product_row = mysql_fetch_array($product_query);
//Query treat_period table
}
?>
I want to use $product_id variable on the next php block of code but but it is not recongnised at all. Somebody please help me.
<?php
require_once'session.php';
$query=mysql_query("SELECT * FROM product_addon WHERE memberid='$ses_id' && productID='$product_id'");
while($row=mysql_fetch_array($query))
{
$sta=$row['treat_kind'];
}
?>
PHP lets you use variables throughout the whole file. The reason product_id is not defined is probably because either your query doesn't return any results or product_id is null or blank.
Try this: var_dump($cart_row) right before your query and see if product ID exists and is not empty
I have a section of my website that reads out data to the user.
My current code reads out data in the same order, even when new records are added; they are added at the end of the data that is being echoed out.
I want to read out the most recent data as I am creating a message board.
CODE:
session_start();
$sess = $_GET['id'];
$profile_query = "SELECT * from forum WHERE postee = $sess";
$profile_queried = mysql_query($profile_query);
while($row = mysql_fetch_array($profile_queried))
{
echo '<div class="each_post"><p>'.$row['content'].'</p></div>';
}
Question: How can I echo data from a database in order of recency? Must I add another field to do this?
Your query should be:
$profile_query = "SELECT * from forum WHERE postee = $sess ORDER BY id DESC"
This is what im trying to do.. i got eprofile with a database. the database consist of 2 table which is personal_data and and nationality. 1st user can view thier old personal information then i gonna make update/edit page for them. Nationality is in other table because the nationality in dropdown menu. then the user can change thier personal and information, after they insert new information they clicking the submit button and go to process.php where update process for database occur. my problem is, i dont know how to define/or how to connect two table which is personal_data and nationality in the update query.
code for nationality
<?php
$query = "SELECT nationality_type FROM nationality";
$result = mysql_query ($query); ?>
<select name="personal_nationality" >
<?php while($row = mysql_fetch_array($result)){ ?>
<option value="<?php echo $row['nationality_type']?>" <?php if ( $personal_nationality == $row['nationality_type']){ ?> selected <?php } ?>>
<?php echo $row['nationality_type']?></option>
<?php }?>
</select>
process.php code
<?php
$host="localhost"; // test local
$username="lasadmin"; // Mysql username
$password="lasadmin"; // Mysql password
$db_name="eprofile"; // Database name
$db = mysql_connect($host, $username, $password);
$link = mysql_select_db($db_name,$db);
$personal_designation = $_POST['personal_designation'];
$personal_department = $_POST['personal_department'];
$personal_job_grade = $_POST['personal_job_grade'];
$personal_emp_group = $_POST['personal_emp_group'];
$personal_current_company = $_POST['personal_current_company'];
$personal_work_location = $_POST['personal_work_location'];
mysql_query("UPDATE personal_data SET personal_designation = '".mysql_real_escape_string($_POST["personal_designation"])."', personal_department = '".mysql_real_escape_string($_POST["personal_department"])."', personal_job_grade = '".mysql_real_escape_string($_POST["personal_job_grade"])."', personal_emp_group = '".mysql_real_escape_string($_POST["personal_emp_group"])."', personal_current_company = '".mysql_real_escape_string($_POST["personal_current_company"])."', personal_work_location = '".mysql_real_escape_string($_POST["personal_work_location"])."' WHERE LAS_login_id = '".mysql_real_escape_string($_POST["LAS_login_id"])."'");
$personal_full_name = $_POST['personal_full_name'];
$personal_title = $_POST['personal_title'];
$personal_date_birth = $_POST['personal_date_birth'];
$personal_marital_status = $_POST['personal_marital_status'];
$personal_nationality = $_POST['nationality_type'];
mysql_query("UPDATE personal_data SET personal_full_name = '".mysql_real_escape_string($_POST["personal_full_name"])."', personal_title = '".mysql_real_escape_string($_POST["personal_title"])."', personal_date_birth = '".mysql_real_escape_string($_POST["personal_date_birth"])."', personal_marital_status = '".mysql_real_escape_string($_POST["personal_marital_status"])."', nationality_type = '".mysql_real_escape_string($_POST["personal_nationality"])."' WHERE LAS_login_id = '".mysql_real_escape_string($_POST["LAS_login_id"])."'");
?>
when i trying to change the information(testing), this error is show
-Notice: Undefined index: nationality_type in C:\wamp\www\eprofile\process.php on line 26
this is code for line 26
$personal_nationality = $_POST['nationality_type'];
can u tell me what is the problem, and what is the solution for this problem? what should i do on defined index??
At first I would recommend to escape the content that you receive by the $_POST variables.
You don't need to copy it into extra variables. (Unless us use it for something different)
Second problem is that $LAS_login_id is not initialized, has no value, so your UPDATE statement won't update anything.
//simple update
mysql_query("UPDATE mytable SET
myvalue = '".mysql_real_escape_string($_POST["my_value"])."'
WHERE mycriteria = '".mysql_real_escape_string($_POST["my_criteria"])."'");
And there should be an array with nationality_type as index which is undefined too.
You have two problems...
THe first one is in your UPDATE sql query.
WHERE LAS_login_id= '$LAS_login_id'
Where did you find the $LAS_login_id ? You are not defining it anywhere that i can see...
The second problem is with your index nationality_type which you have not included in the code above...
Hope this helps
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
}