Jump to content

Get id from one page and retrieving all info on that ID on different page


echosara
Go to solution Solved by mac_gyver,

Recommended Posts

Hi,

 

     I am currently working on a inventory page and a page which gets into the details of that particular product. Basically on one page i have a list of products and when i click on one of the products it takes me to another page when has more detail about the product (retrieved from the database). The problem which i am currently stuck on is when i click on say the first product (id=1) it will take me to the second page and show me product 2 (id=2) instead of the first product. here is what i have so far if anyone can assist it would be great.

 

 

this is in my first inventory page.--

 

  <div id="viewdetails"><a href="<?php echo BASE_URL .'view/singleproda.php?id='. $info["id"];?>"> View Details</a></div>

 

 

this is how my second page looks--.:

 

include(ROOT_PATH ."controller/mainfunction.php");
$result = get_products_all();
 
 
if (isset($_GET["id"])) {
$proda_id = $_GET["id"];
if (isset($result[$proda_id])) {
$product = $result[$proda_id];
}
}
 
if (!isset($product)) {
header("Location: inventory.php");
exit();
}
 
 
<div id="singprod"> <img src="<?php echo $product["picc"];?>" > </div>
<div id="productid"> <?php echo "id"."$space" .":". $product["id"]; ?></div>
<div id="productname"> <?php echo "info" ."$space" .":". $product["product"];?></div>
<div id="productinfo"><?php echo "Description". "$space". "Description" .":". $product["description"];?></div>
<div id="productprice"><?php echo "Product Price" ."$space".":". $product["price"];?></div>

 

 

 

--------------------------------------------------------------

on the url on the second page it shows the correct ID however when i look at the information from the page ( the last 5 lines , pic, id, product, description...etc) it shows the information for id=2.  This same thing happens when i click on any product ( eg id=4 or id=5) it would always give me the product information for the ID after that id i have clicked on. Any idea whats wrong with this?

Link to comment
Share on other sites

 

this is how my second page looks--.:

 

$result = get_products_all();

You need to be running a query which returns the row in the products table that matches the product id that is passed in the url.

 

Example

<?php

// connect to databae
$pdo = new PDO($dsn..., $user..., $password...);

// get the product id from url
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
    // run prepared query, returne the row where the product_id matches
    $stmt = $pdo->prepare('SELECT * FROM products WHERE product_id = ?');
    $stmt->execute(array(intval($_GET['id'])));

    // get the product data
    if(($product = $stmt->fetch(PDO::FETCH_ASSOC)) === false)
    {
          // product requested not found
          header('Location: inventory.php');
          exit();
    }

    // output the product information
?>
<div id="singprod"> <img src="<?php echo $product["picc"];?>" > </div>
<div id="productid"> <?php echo "id"."$space" .":". $product["id"]; ?></div>
<div id="productname"> <?php echo "info" ."$space" .":". $product["product"];?></div>
<div id="productinfo"><?php echo "Description". "$space". "Description" .":". $product["description"];?></div>
<div id="productprice"><?php echo "Product Price" ."$space".":". $product["price"];?></div>
<?php } ?>

That is the basic code you need for your second page.

Edited by Ch0cu3r
Link to comment
Share on other sites

You're going about this all wrong.  First you need to edit your get_products_all() function to allow for it to just get one row of data, the one you need based on the id.  It's dumb to get all the products in the result if you only need one of them.  The reason you're displaying product 2 instead of one is cause of the "index" difference int the $result.  $result is starting at index 0 not 1 like your product id is looking for, so it's doing it correctly based on what you asked it to do, you're not doing it right is the problem.

 

Here is the correct way to do this.  If you post your get_products_all() I can show you how to do that too most likely, or you can figure it out yourself which would be the better thing to do.

<?php
if (empty($_GET["id"])) { // This will check if it's set and empty
	header("Location: inventory.php");
	exit();
}
else {
	$id = (int)$_GET['id']; // This will convert it to an integer so it's not able to do a sql injection attack.
	$result = get_products_all($id); // This is why you need to edit your function to allow for the $id to pass and only get that row from the db.
?> 
	<div id="singprod"> <img src="<?php echo $product["picc"];?>" > </div>
	<div id="productid"> <?php echo "id"."$space" .":". $product["id"]; ?></div>
	<div id="productname"> <?php echo "info" ."$space" .":". $product["product"];?></div>
	<div id="productinfo"><?php echo "Description". "$space". "Description" .":". $product["description"];?></div>
	<div id="productprice"><?php echo "Product Price" ."$space".":". $product["price"];?></div>
<?php
}
?>

Link to comment
Share on other sites

Ok, i tried this and it now doesn't  display any variables on the second page. this is the coding

 

First page inventory.php

 <div id="viewdetails"><a href="<?php echo BASE_URL .'view/singleproda.php?id='. $info["id"];?>"> View Details</a></div>

second page singleproda.php 

 

function get_product_id($proda_id) { 

$connect = mysql_connect("localhost","root","") or die ("couldn't connect!");
mysql_select_db("test") or die("couldn't find db");


$product = mysql_query('SELECT * FROM products WHERE id = "$proda_id"');

return $product;
}




if (isset($_GET["id"])) {
$proda_id =(int)$_GET["id"];
$product = get_product_id($proda_id);

//if (isset($result[$id])) {
//$product = $result[$id];
//}
}

if (!isset($product)) {
header("Location: inventory.php");
exit();
}



<div id="singleproduct">



      <div id="singprod"> <img src="<?php echo $product["picc"];?>" > </div>
                <div id="productid"> <?php echo "id"."$space" .":". $product["id"]; ?></div>
<div id="productname"> <?php echo "info" ."$space" .":". $product["product"];?></div>
<div id="productinfo"><?php echo "Description". "$space". "Description" .":". $product["description"];?></div>
<div id="productprice"><?php echo "Product Price" ."$space".":". $product["price"];?></div>
                
                </div>
 
 
 
what am i doing wrong?

 

 

Link to comment
Share on other sites

In your function you're only returning the resource, not the results of the query. Replace the return line in the function with this.

return mysql_fetch_assoc($product);

Also this line is not what you want.

if (!isset($product)) {
header("Location: inventory.php");
exit();
}

Why, cause no matter what $product isset cause you are defining it just above.  You want to know if it's empty, meaning no rows have been returned from the query.

if (empty($product)) {
header("Location: inventory.php");
exit();
}
Link to comment
Share on other sites

Ok, i added that and i still get a error on a few lines.


if (isset($_GET["id"])) {
	$proda_id =(int)$_GET["id"];
	$product = get_product_id($proda_id);
	
	//if (isset($result[$id])) {
	//$product = $result[$id];
	//}
}

if (!isset($product)) {
	header("Location: inventory.php");
	exit();
}

<div id="singleproduct">


 
   	 			<div id="singprod"> <img src="<?php echo $product["picc"];?>" > </div>
                <div id="productid"> <?php echo "id"."$space" .":". $product["id"]; ?></div>
				<div id="productname"> <?php echo "info" ."$space" .":". $product["product"];?></div>
				<div id="productinfo"><?php echo "Description". "$space". "Description" .":". $product["description"];?></div>
				<div id="productprice"><?php echo "Product Price" ."$space".":". $product["price"];?></div>
                
                </div>

i pretty much get an "undefined index error on each div... singprod,productid, productname, productinfo, productprice..(above)

 

 

 

(below) is the function which does the query

function get_product_id($proda_id) { 

$connect = mysql_connect("localhost","root","") or die ("couldn't connect!");
	mysql_select_db("test") or die("couldn't find db");
	
	
$query = mysql_query('SELECT * FROM products WHERE id = "$proda_id"');
while($product[]=mysql_fetch_array($query));

return $product;
}

anyone know why i get those errors?

 

 

Link to comment
Share on other sites

  • Solution

the current errors are because your sql query is not matching any rows.

 

your code should ALWAYS test if the query failed due to an error AND when it does run without any errors, your code should test how many rows the query matched and take an appropriate action in either case. if your code did have logic in it to test for these two things, it would be self-diagnosing and would tell you why it isn't doing what you expect.

 

the reason why it is not matching any rows is because you are using single-quotes to start and end the sql query statement and the php variable in it is not being evaluated and replaced with its value. the query being ran is literally - SELECT * FROM products WHERE id = "$proda_id", and since id will never be the string of characters $,p,r,o,d,a,_,i,d, the where clause is false.

 

some tips -

 

1) you should always form the sql query statement in a php variable. this separates it from the code running the query so that you can echo/log it to see what it actually is and so that you can copy/paste the sql statement and run it directly against your database to see if it does what you expect.

 

2) you should always use double-quotes to start and end the sql query statement. this will cause any php variables inside the sql query statement to be evaluated and replaced with their value.

 

3) you should always use single-quotes inside the sql query statement around string data. since the id is numerical, you shouldn't have anything around the value inside the sql query statement.

 

next, your code has other functional problems.

 

1) you should not create the database connection inside your function. this results in repeated code and settings, in every function that needs to use the database (what happens if you ever need to change how the connection is made or the connection credentials? you should only have ONE place in all your code where you would need to change these things), and results in repeatedly making database connections, which take a relatively long time.

 

your application should create ONE database connection and use that ONE connection everywhere it is needed in the code. to pass the database connection into your functions, you would pass it as a call time parameter, like the $proda_id variable is being use now. since the database connection is required for any database dependent function or operate, it should be the first parameter in the list, for consistency reasons.

 

2) the purpose of the get_product_id() function is to return data for ONE id. it should not have a while(){} loop (there's also a problem with the while loop, see the next item in this list.) all you should be doing is to fetch and return the ONE expected row that the query returns.

 

3) your current while(){} loop is returning the expected data as an array of arrays (when the query actually works), and is also returning a final NULL entry in that array that will cause any code that access the final entry to throw errors. when you fix item #2 above in this list, this problem with go a way and your code will get one single row array back from the function and you will be able to access the elements in it using things like $product["id"].

 

4) lastly, the mysql_ functions are depreciated and obsolete. you should not spend your time trying to learn them as they will be removed in a future php version and the time you spend learning them will be wasted. you should be learning and using either the mysqli_ or PDO database functions.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.