while inside another while in php - php

I have created a blog in php. Users can view posts of their friends and they can "like it", like you do in facebook. Under each post there is a link that when a user press it, the user can see all users like this certain post. Table comments holds all posts: comments(comments_id, comment, user) and table likes(like_id, user, the_comment_id) holds all likes for each post.
I have the following problem. Lets say that users 23, 30 like first post. User 30 likes second post. If I press on link for the first post to see pleople like it, it gives me 23 and 30. But if I click on second post, it gives 23, 30 and 30 and not only 30 as it should give me.
Probably the problem is with "while"... any idea how to fix this?
This is my php code for this:
<?php
$sql = mysql_query("SELECT * FROM comments");
// starts a while loop that prints all posts...
while ($row= mysql_fetch_assoc($sql)) {
$comment_id = $row['comments_id'];
//... prints post details succesfully
$comments .= ".$row['comment'].";
// here starts the process for the link, that user will press it, it will get all users likes this certain post
$favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}' ");
while($e = mysql_fetch_array($favorites)){
$like_users = $e['user'];
$array[]=$like_users;
}
$arstring = implode('</br>',$array);
$comments .= <<<EOD
// here starts link, that press and see all people like this comment
$arstring
EOD;
} //end while

You should section off your like-array to be per-comment. Right now it's a single array for all comments/posts. So basically just clear it before starting the 2nd while loop.
You can do it like this:
<?php
$sql = mysql_query("SELECT * FROM comments");
// starts a while loop that prints all posts...
while ($row= mysql_fetch_assoc($sql)) {
$comment_id = $row['comments_id'];
//... prints post details succesfully
$comments .= ".$row['comment'].";
// here starts the process for the link, that user will press it, it will get all users likes this certain post
$favorites = mysql_query(" SELECT * FROM `likes` WHERE `the_comment_id`='{$row['comments_id']}' ");
$array = array(); // empty the list of any earlier users
while($e = mysql_fetch_array($favorites)){
$like_users = $e['user'];
$array[] = $like_users;
}
$arstring = implode('</br>',$array);
$comments .= <<<EOD
// here starts link, that press and see all people like this comment
$arstring
EOD;
} //end while
On a sidenote: you really should not use the mysql extension anymore. It is officially deprecated. Instead use the MySQLi or PDO extensions. These are both faster and safer.

Related

PHP highlight selected item

Just like the image above, when the user clicks one of the list on the right side, it highlights the selected one.
$result = mysqli_query($con, "SELECT * FROM contacts") or die(mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$company = $row['eyo_company_name'];
$id = $row['con_id'];
$editLinks .= "\n\t$company<br>";
}
this is how I brought the list out from the database. Would there be any way I could add a class or add b tag on selected one only ?
If I understand correctly, you are trying to highlight one of the links output by PHP. To do so you will need to know which one to highlight.
If you have a GET variable set to the current contact ID, you could do something like this:
while($row = mysqli_fetch_array($result)){
$company = $row['eyo_company_name'];
$id = $row['con_id'];
//let's check if we've pre-selected a company
// and if so, is this the company we selected?
if (true === array_key_exists('CURRENT_COMPANY_ID', $_GET) && $id === $_GET['CURRENT_COMPANY_ID']) {
//we did select this company for this PHP request
// let's make the HTML output custom to highlight the selected company
$editLinks .= "\n\t<strong>$company</strong><br>";
} else {
$editLinks .= "\n\t$company<br>";
}
}
This example expects that your request to the PHP script generating your list of links will include CURRENT_COMPANY_ID=<ID HERE> in the URL.
For example, if the URL for the request that generates your list of links looks like this:
/getMySuperAwesomeList.php
It would need to look like this:
/getMySuperAwesomeList.php?CURRENT_COMPANY_ID=123
Where 123 matches the con_id of the record you want to highlight.
I chose to use array_key_exists() to make sure that the request actually included the CURRENT_COMPANY_ID data in the URL. Here is documentation for that function: https://www.php.net/array_key_exists

Echoing out most recent database records?

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"

Mysql Pageviews update only per session

just got help with making my code for pageviews work... and now i would like the pageviews only count 1 for each session / ip.
In my users (news.users) table i have these cells available for use: (tried to set up something earlier that didnt work out so these are not in use)
ip_reg, ip_visit, dtreg, dtvisit, visits, pass
The code i have that is now working looks like this :
//Adds one to the counter
mysql_query("UPDATE news SET posts = posts + 1, published=published, last_edit=last_edit WHERE id=$id");
//Retreives the current count
$count = mysql_fetch_row(mysql_query("SELECT posts FROM news WHERE id=$id"));
//Displays the count on your site print
echo "<label>Viewed: ";
echo $count[0];
echo " times</label>";
?>
Can i use some of the unused cells in users to stop a user from reloading the page to get higher views on a page? And how do i do it :P
Like I suggested I would put the read news articles in the user's session. Try this:
if (!isset($_SESSION['read_news']) || !is_array($_SESSION['read_news'])) {
$_SESSION['read_news'] = array();
}
if (!in_array($id, $_SESSION['read_news'])) {
$_SESSION['read_news'][] = $id;
mysql_query("UPDATE news SET posts = posts + 1 WHERE id=$id");
}
If this doesn't work, you don't have sessions enabled and you should put session_start(); somewhere in the top of your project. Make sure that line is called in each request.

How to make sure an item already pulled from mysql doesn't get pulled again

I'm making a related stories section which uses the tags in a post to go through and find other stories with similar tags.
I want to make sure that I'm not pulling the same story multiple times if it shares more than one tag with another post.
So it's basically
foreach($tags as $t) {
$getStories = mysql_query("SELECT * FROM `posts` WHERE `tags` LIKE '%$t%' LIMIT 2");
while($related = mysql_fetch_array($getStories)) {
echo $related['title'];
}
So I pull 2 related stories based on the first tag, now, when it goes around through next loop for the second tag, how can I make sure that a story pulled the last time doesn't get picked the second or third time. I do have a unique ID just called 'id', just not sure what to do with it in this situation.
Thanks!
What you could do is fetch all related articles at once:
$tagsClause = '';
foreach ($tags as $t) {
$tagsClause .= " OR tags LIKE '%$t%'";
}
$tagsClause = substr($tagsClause, 4); // Remove first ' OR '
$getStories = mysql_query('SELECT * FROM `posts` WHERE ' . $tagsClause);
while($related = mysql_fetch_array($getStories)) {
echo $related['title'];
}
However, this does not account for your use of LIMIT.
EDIT
Apparently this did not pose a problem, cf. comments.
Use UNIQUE.
SELECT UNIQUE(post_id), [other stuff] FROM posts WHERE [...]
i think you can make an array containing the ids you have selected, when you process a tag, check the id is not in the selected array, but it's not efficient.
just like this:
$ids = array();
foreach($tags as $t) {
$getStories = mysql_query("SELECT * FROM `posts` WHERE `tags` = '$t' LIMIT 2");
//here to check and add id to array ids
while($related = mysql_fetch_array($getStories)) {
echo $related['title'];
}
}

Need Associated ID Added to a While Loop (php)

Been trying to get my head around while loops for the last few days but the code seems very inefficient for what I'm trying to achieve. I'm assuming I'm over-complicating this though nothing I've tried seems to work.
Each topic in my forum can have related topic IDs stored in a separate table. A post ID is also stored in this table, as that specific post references why they are considered related.
DB Table contains only: topic_id, related_id, post_id
// Get related IDs and post IDs for current topic being viewed
$result = $db->query('SELECT related_id, post_id FROM related_topics WHERE topic_id='.$id.'');
// If related topics found, put both of the IDs into arrays
if ($db->num_rows($result)) {
while($cur_related = mysql_fetch_array($result)){
$reltopicarray[] = $cur_related['related_id'];
$relpost[] = $cur_related['post_id'];
}
// If the first array isnt empty, get some additional info about each related ID from another table
if(!empty($reltopicarray)) {
$pieces = $reltopicarray;
$glued = "\"".implode('", "', $pieces)."\"";
$fetchtopics = $db->query('SELECT id, subject, author, image, etc FROM topics WHERE id IN('.$glued.')');
}
// Print each related topic
while($related = mysql_fetch_array($fetchtopics)){ ?>
<?php echo $related['subject']; ?> by <?php echo $related['author']; ?>
// Id like to show the Post ID below (from the array in the first while loop)
// The below link doesnt work as Im outside the while loop by this point.
<br />View Relationship
<?php } ?>
The above currently works, however I'm trying to also display the post_id link below each related topic link, as shown above.
if you change the second while loop to something like this:
<?php
$i = 0;
while($related = mysql_fetch_array($fetchtopics)){
//show view link
// [...]
//show the view related link
?>
View Relationship
<?php
//increment the i so that you can get the next post in the next iteration of the loop
$i++;
}
?>
[sidenote]
You probably should not be doing database queries in the same location you are generating the html for future-you's sanity.
[/sidenote]
[edit]
You could also do it all as one query:
SELECT related_topics.related_id,
related_topics.post_id,
related_topics.topic_id,
topics.subject,
topics.author,
topics.image,
topics.etc
FROM related_topics
LEFT JOIN topics ON topics.id = related_topics.topic_id
WHERE topic_id= $id
Then you only have to loop through it once for all of the links.

Categories