user6362236 user6362236 - 5 months ago 16
Javascript Question

save page id in cookies and retrieve that certain id's row from database in other page

hi every one i am designing a real estate website i have many ads in my website and when user click on a certain ad it goes to another page "viewmore.php" which gives user more details about that certain ad. so far i create a 'favorite' or 'save' button on viewmore page that will save the selected page title in a certain page based on cookies for user to read later.
Now i want to send ad's id to the favorite page when ever user click on "add to favotites" thus based on id i can fetch that certain ad data from database . like the page title i want to do this based on cookies.
can i do this? how? this is my current code



//viewmore.php
<?php
error_reporting(0);
include("config.php");
(is_numeric($_GET['ID'])) ? $ID = $_GET['ID'] : $ID = 1;
$result = mysqli_query($connect,"SELECT*FROM ".$db_table." WHERE idhome = $ID");
?>
<?php
error_reporting(0);
include("config.php");
(is_numeric($_GET['ID'])) ? $ID = $_GET['ID'] : $ID = 1;
$result = mysqli_query($connect,"SELECT*FROM ".$db_table." WHERE idhome = $ID");
?>
<?php $row = mysqli_fetch_array($result):
$price=$row['price'];
$rent=$row['rent'];
$room=$row['room'];
$date=$row['date'];
?>
<?php
$cookie_name = "favoritepost";
$cookie_value ="$ID";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<?php
echo"price";
echo"room";
echo"date";
?>




and this is my javascript code which i save page title and page url in cookies after user click on add to favorites

any idea thank u

ddb ddb
Answer

The setcookie() function must appear BEFORE the <html> tag.
After setting it, you can read the cookie every where in your php scripts in this way

$_COOKIE[$cookie_name]

PS: of course I suppose cookies are enabled on your browser.