session variable between 2 divs on same page? - php

im trying to pass a session between 2 div on the same page.
i have links, when i click on one i want the id to pass to the other div to populate it with the info from the link, but it doesnt pass!!
this is the code from my links div
$q =mysqli_query($link, "SELECT * FROM products WHERE status = 1 ORDER BY id DESC");
while($row = mysqli_fetch_array($q)){
$data = $row['image'];
$file = substr($data, strpos($data, "/") + 1);
$_SESSION['id']=$row['id'];
echo"<div class='homedogs'>",
"<a href='merchandise.php' class='productchoice'>",
"<img class='nailthumb-container3' src='$file' alt='{$row['name']}. Image' />",
"</a>",
"<br />",
'NAME: ',$row['name'],"<br />",'PRICE: ',$row['price'],
"</div>";
}
}
and this is other div that i want to use the session in
include 'inc/connect.php';
$q = mysqli_query($link, "SELECT * FROM products WHERE id = '".$_SESSION['id']."'") or
die (mysql_error());
while($row = mysqli_fetch_array($q)){
$data = $row['image'];
$file = substr($data, strpos($data, "/") + 1);
echo"<div class='rehomediv'>",
"<img class='nailthumb-container2' src='$file' alt='{$row['name']}. Image' />","<br
/>",
"<div class='nameagesex'>",
"<div class='item_name'>{$row['name']}</div>",
"<br />",
"<span class='item_price'>{$row['price']}</span>",
"</div>",
"<div class='description'>",
nl2br($row['description']),
"</div>",
</div>;
im sure its simple enought but i cant get it! can anyone help?
thanks
EDIT!!!!!
on page load, pid is not set so i get an error, is there anyway to have it that if pid is not set then it just display the last record?
for anyone confused by this edit, check the accepted answer..

You are assigning $_SESSION['id'] multiple times inside a while loop. This will end up keeping only the last value, provided that you do session_start(), as you claim you do.
If you want this to work, don't use $_SESSION, but a GET query instead. Change your link-producing code to:
"<a href='merchandise.php?pid={$row['id']}' class='productchoice'>"
...and, in merchandise.php check $_GET['pid'] to determine the product id being requested:
if(isset($_GET['pid']))
// show corresponding product (your second listing)
else
// show something else, i.e. the product catalog (your first listing)

Related

Calling from a MySQL/PHP array multiple times in a page

I'm probably asking a very simple question here - I know the basics of calling an array but I think I'm probably not doing it in the most efficient way... I'm calling some data into an array at the start of my page and then I want to be able to use this data-set multiple times throughout the page without wrapping everything in PHP if possible.
At present I'm doing it like this -
A variable ('video') is passed to my page through the URL which I get like so:
<?php
$video = $_GET['video'];
?>
My <title> tag is pulled from the selected database (also titled 'video')
<?php
$title = mysql_query("SELECT * FROM video WHERE ID = '{$video}'") or die(mysql_error());
mysql_real_escape_string($video);
while($head = mysql_fetch_array( $title )) {
echo "{$head['title']} - BY XXXXX</title>";
echo "<meta property=\"og:title\" content=\"{$head['title']} - BY XXXX\"/>";
}
?>
I then want to use the {$video} data later on the same page, but defining a slightly different variable like so:
<?php
$data = mysql_query("SELECT * FROM video WHERE ID = '{$video}' ORDER BY added DESC") or die(mysql_error());
mysql_real_escape_string($video);
while($info = mysql_fetch_array( $data )) if ($info['ytembed'] == 'yes') {
echo "{$info['embedcode']}";
echo "<div class=\"videobox1\">";
echo "<div class='video-title'>{$info['title']}</div>";
echo "<div class='video-subtitle'>{$info['subtitle']}</div>";
echo "<div class='video-credits'>{$info['cast']}</div>";
echo "<div class='back'>«back</div></div>";
} else {
echo "no embed code";
}
?>
So at the moment every time I want to pull from that data I'm calling the whole array again - it would be amazing if instead of doing this I could just print/echo selected items
Is there a way to make my code more efficient and do this?
I'm also looking to Validate the ID and if it doesn't exist within the video DB send the user to a 404 page - but perhaps that's a separate question.
Hello this is refined code
Replace first 1 with this.
$video = $_GET['video'];
$video = mysql_real_escape_string($video);
$videodata = mysql_query("SELECT * FROM video WHERE ID = '{$video}' LIMIT 1") or die(mysql_error());
// execute the query and check if video id exist or not
if(mysql_num_rows($videodata) == 0){
// 404 redirect code.
}
Replace Second with
$videodataArray = array(); // created array for storing video data
while ($head = mysql_fetch_array($videodata))
{
$videodataArray = $head ; // store the value in video data array for to use in fulll page
echo "{$videodataArray['title']} - BY XXXXX</title>";
echo "<meta property=\"og:title\" content=\"{$videodataArray['title']} - BY XXXX\"/>";
}
Replace last one with
echo "{$videodataArray['embedcode']}";
echo "<div class=\"videobox1\">";
echo "<div class='video-title'>{$videodataArray['title']}</div>";
echo "<div class='video-subtitle'>{$videodataArray['subtitle']}</div>";
echo "<div class='video-credits'>{$videodataArray['cast']}</div>";
echo "<div class='back'>«back</div></div>";

Only the last image displays from database

I asked this question before but no one could help me unfort. I have images and headings coming from database now the problem is that only one image is displaying(the last image) i need both to display.
here is my revised code
$query = "SELECT page_title, page_image FROM pages WHERE id='$page'";
$result = mysqli_query($connection, $query);
confirm_query($result);
while ($page_fetch = mysqli_fetch_assoc($result)) {
$page_title = $page_fetch['page_title'];
$images = $page_fetch['page_image'];
echo "<div class=\"content \">";
echo "<h3 class=\"words\"> $page_title </h3>";
echo "<img src='pics/" . $images . "' width=\"340\" height=\"252\" alt=\"\" />";
echo "</div>"; //end box
} // close while loop
here is my database for pages
page_id id page_image page_title
1 1 ocean.jpg have a look at the ocean
2 1 house.jpg The house
just some extra info the images must display dynamically , as they coming in from a form to db to this page
Your are returning your images from your query.
Check the view source page, You will find your error their.
Your returing image name will not match with the image which you got in the folder. (For the second one)

how to link a database item to a link

I am designing a system for a recruitment agency and have a search page where the "applicants" can search for a job and apply, the search results is structured:
-Job_Title
-Job_description
-Apply link
This is the same for every result. Code for the above mentioned:
$num_rows = mysql_num_rows($query) or die(mysql_error());
if ($num_rows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
echo "<h2><a href='#'> $title</a> </h2>";
echo "$description <br /> <br />";
echo"<a href='../View/applicationForm.php' class='link-button right'><span>Apply</span></a>";
Now my problem is that I don't know how to make the Apply link go to each Jobs respective Application form. How can I make the link different for each advert or link the application form to Adv_title in the database?
In order to identify each job in applicationForm.php, you need to pass a parameter that identifies each job via $_GET. This parameter should be unique for each job, so it could be the id field in database that you mention, or it could be the title, assuming that you are checking title uniqueness whenever you create a new job.
So, if you want to use id, your code would look like this (assuming that your field is named id):
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$id = $row['id'];
echo "<h2><a href='#'> $title</a> </h2>";
echo "$description <br /> <br />";
echo"<a href='../View/applicationForm.php?id=$id' class='link-button right'><span>Apply</span></a>";
If, for any reason, you don't want end users to view your ids, you can always encrypt them before showing, and decrypt them in applicationForm.php.
In hyperlink tag give the value of the link to redirect to instead of #.
Like you have Adv_Title and Adv_desc field you will need to keep the link too and then you can fetch it and use it.
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$link=$row['Adv_link'];
echo "<h2> $title </h2>";
$num_rows = mysql_num_rows($query) or die(mysql_error());
if ($num_rows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$id = $row['Adw_id'];
$link = "/$id/View/applicationForm.php";
echo "<h2> $title </h2>";
echo "$description <br /> <br />";
echo"<a href='../View/applicationForm.php' class='link-button right'><span>Apply</span></a>";
if application from is different according to the job adv, you better should have a field in the database table to consider about different application form according to each Adv_title.
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$id = $row['Adw_id'];
//if $row['url_link'] is full url
$link = $row['url_link']; // full link
//if $row['url_link'] is just and identifier
// some conditions goes here
......
echo "<h2> $title </h2>";
echo "$description <br /> <br />";
echo "link";
If you really want to hide the id, you can set a server side session variable holding the current job id. And the pick it up on the page that generates the application form. ALternatively, just include it as part of the URL as manuelpedrera shows.

Display image on php mysql blog based on username of post

Thanks in advance!
I have a simple mysql and php blog that I built based on a tutorial I found online. What I would like to be able to do, but have no idea how to go about it, is this:
I would like a picture (avatar) to be displayed with each comment on each post. The picture that is chosen would be based off of the name in the Posted By: area of the comment. So for instance: Let's say me, the admin, leaves a comment on the thread. My name is automatically pulled in via a '$_SESSION' variable so I don't have to worry about entering that each time. When the comment is displayed on the blog thread page, it shows Commented on By: Admin. This name is stored in the db and pulled in with the a php echo statement.
So what I want this avatar code to be able to do is
1) look at the area where the Commented on By: text is
2) read the text
3) see that it says Admin and display the admin.png image next to it. If it sees anything other than Admin in the Commented on By: area, then it will display something like guest.png
Here is a snippet of code I found in my stackoverflow and google searches. It works but it pulls in the guest image 6 times, then the actual admin.png image, and then the guest image 3 more times. And it displays this way on EACH comment on EACH thread! And when I add a new thread and a new comment to that thread, it adds the guest image again at the end of the multiple images being displayed on each comment. Did I set it up wrong?
<?
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) != 0) {
$counter = $starting + 1;
$pathImg = "images/";
while ($row = mysql_fetch_array($result)) {
//calculate url image
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
?>
<img src="<?=$pathFile?>" alt="<?=$row['comment_user']?>">
</p>
<?
$counter++;
}
}
?>
This displays out as (Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Admin Image)(Guest Image)(Guest Image)(Guest Image).
Any help on throwing something together would be great! Trying to keep it simple to!
EDIT:
This is how the comments are displayed, along with the code from FlyingGuy's answer.
<?php
foreach ($post['comments'] as $comment){
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$commentCount++ ;
$pathImg = "images/";
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
?>
<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
<p><?php echo $comment['body']; ?></p>
<hr />
<?php
}
?>
This is how the functions look for displaying and adding comments:
function get_comments($pid){
$pid = (int)$pid;
$sql = "SELECT `comment_body` AS `body`, `comment_user` AS `user`, DATE_FORMAT(`comment_date`, '%m/%d/%Y') AS`date` FROM `comments` WHERE `post_id` = {$pid}";
$comments = mysql_query($sql);
$return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){
$return[] = $row;
}
return $return;
}
// adds a comment
function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}
$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentities($user));
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
return true;
}
?>
Look what you are trying to do is select the image that matches the name of the user in the current row of your result set. So you will set your image file variable as appropriate for each row and you are sending that to the browser.
For starters and can see the probability of case issues here. Are all user names forced to lower case and all image names forced to lower case? If this is on a linux box that is a land mine on windows not so much, but this should be taken into account.
It will set an image name for each row of your queries result set so it will look like:
[image] [comments]
[image] [comments]
[image] [comments]
if you have three rows in your result set.'
Personally I avoid all of the turning php on and off all over the place. Concat a single string and then simply echo it out for each row. So I would code it like so:
<?
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$commentCount++ ;
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
So I have eliminated a lot of things from your code example like counters etc. You don't really need to check and see if there are rows since the while loop simply will not execute of there are no rows so you will simply have a question of comment with no subordinate comments and it will only send the image link if there are comments.
No if it were me doing this I would create an avatar file name is the user table and store the path to those as part of the system configuration which would be part of the global set of variables that are always present. Your query would then join in the users table and the image name or guest image would be in your result set. A bit more complex but much cleaner and it simplifies your code.
One of the reasons I don;t like dynamic typing. $row was being mutated to an array of ALL the rows..

Adding Page Counter to Each Classified Ad

I am trying to add a page counter to each classified Ad just like to one on ebay for example. There is a page counter that increases whenever a user clicks on an item.
Here is why I have a problem:
itemlist.php
$query="SELECT post_id, title FROM md_post WHERE category='cars' ORDER BY timeStamp desc";
$result= mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo "<a href='itemdescription.php?id=".$row['post_id']."'>". $row['title']."</a>";
so When I click on an item title with id of 3, i would be direction to the itemdescription.php?id=3
My problem is when I add a page counter to itemdescription.php, I get a counter that increments even when I click on different items.
the counter will be 1 for itemdescription.php?id=3
and 2 for itemdescription.php?id=4
I want each ad to have a stand-alone page counter
UPDATE:
Sorry I did not include the code for itemdescription.php page since there is no much in it. Here it is:
<div id="content">
<?php
$query="SELECT name, email, category, region, city, title, price, description FROM md_post WHERE category='cars' AND post_id='$_GET[id]'";
$result= mysql_query($query) or die (mysql_error());
$row = mysql_fetch_array($result);
echo $row['category'] . " in ". $row['city'];
echo $row['title']. " - price is -". $row['price']."$"." ". "<br /><br />";
echo "description"."<br /><br />";
echo $row['description'];
echo $row['name'] . " - ". $row['email']. " region:". $row['region'] . "<br /><br />";
This page is only displaying the ad. e.g. displaying info like price, title, city ...etc
I want to include a stand-alone page counter at the bottom of this page, but when I tried, the counter was not unique for a specific item/ad. It was shared by all items/ads
$_SERVER['REQUEST_URI']
gives you the URL with parameters. you need to update your counter unique to that, not without parameters. if you share more of your codes, we can help you with integration.
I solved it. Thanks for your help anyway. This code below will create a text file that checks the id of the url and counts hits based on the unique ad id. This will prevent mixing counting ads or posts.
<p> this ad has this number of visits </p>
<?php
//--------------------Page counter-------------------------
$stored = "counters/".$_GET['id'].".txt";
function displayHitThingy($stored) {
$fp = #fopen($stored,"r");
$stuff = #fgets($fp,9999);
#fclose($fp);
$fp = fopen($stored,"w");
$stuff += 1;
print "$stuff";
fputs($fp, $stuff);
fclose($fp);
}
displayHitThingy($stored);
//________________________________________________________________________
?>

Categories