PHP Using while loop to count rows - php

I'm attempting to show notifications when one user follows another user. I want to check the notification table to see when the receive_id is the same as the logged in users id ($user_id). The issue is that I'm not sure how to write the while loop to check how many times these values are the same. Currently, the loop is unending. Here is what I have so far:
<?php
$stmt = $user_home->runQuery("SELECT * FROM notif_follow WHERE receive_id=:rid ORDER BY id DESC LIMIT 5");
$stmt->execute(array(":rid"=>$user_id));
$notif = $stmt->fetch(PDO::FETCH_ASSOC);
$id = $notif['id'];
$send_id = $notif['send_id'];
$receive_id = $notif['receive_id'];
$status = $notif['status'];
if($notif !== false)
{
while($receive_id = $user_id)
{
echo '
<li>
<a href="#">
<strong>'.$notif['send_name'].'</strong><br />
<small><em>'.$notif['receive_name'].'</em></small>
</a>
</li>
<li class="divider"></li>
';
}
}
else
{
echo '<li>No Notification Found</li>';
}
?>

Related

PHP array not working as expected

I am making a list in messages.php which displays all the active conversations the logged in user ($username) has.
What is classed as an "active conversation"? (What should be listed in the li..)
Assume I am logged in as Alice. Alice sends a message to Fred, this is an active conversation where the $username (Alice) is sending a message to $user (Fred).
Assume I am logged in as Alice. Fred sends a message to Alice. This is also an active conversation.
Summary: Any messages to $username (logged in user) and any messages from $usernameshould be listed, only ONCE.
Current behavior:
Currently, with the code displayed below, an li is being generated for every message I send (every row in the private_messages table relating to the $username).
For example:
Again, assume I am logged in as Alice.
Alice sends a message to Fred saying - "Hello Fred".
One list element is generated stating Fred's firstname.
If, as Alice, I send another message to Fred, it will still display one li element for Fred - Which is good, this is what I want, as the logged in user, I want to see the user I am taking with.
However, if I log off, sign in a Fred, and reply back to Alice, it will generate another li element, but this time with the logged in users credentials, so an li would be generated stating Fred's first name etc.
What I need is all this to be in one li since the conversation is between two people.
This is my current code:
<?php
$displayed = [];
// get number of messages from a specific user to the logged in user
$get_mess = mysqli_query ($connect, "SELECT * FROM private_messages WHERE message_to = '$username' AND message_from ='$user'");
$num_msgs = mysqli_num_rows($get_mess);
// getting all the conversations which concern the user logged on.
$con = mysqli_query ($connect, "SELECT * FROM private_messages WHERE message_from='$username' OR message_to='$username'");
while ($get_con = mysqli_fetch_assoc($con)){
$msg_from = $get_con['message_from'];
$msg_to = $get_con['message_to'];
// get other persons firstname
$u_name = mysqli_query($connect, "SELECT * FROM users WHERE username ='$msg_to'");
$get_cu = mysqli_fetch_assoc($u_name);
$got_ufn = $get_cu['first_name'];
$got_uln = $get_cu['last_name'];
if ($msg_to == $username || $msg_from == $username){
if(!in_array($msg_to, $displayed)) {
echo "<li class='list' role='presentation'>
<div class='parent'>
<div class='disp_pic'>
<img class='img-rounded' src='$profile_pic2'/>
</div>
<div class='user_d'>
<a href='messages.php?u=$msg_from'> $got_ufn $got_uln</a>
</div>";
if ($num_msgs == 0){
// dont display badge
}else {
echo "<span id='num_of_msgs_from' class='badge'>";
if ($user == $user){
$num_msgs == 0;
echo "$num_msgs </span>";
}else {
echo " $num_msgs </span>";
}
}
echo"
</div>
</li>";
$displayed[] = $msg_to;
}
}
} // while closed
?>
You need to get other user with something like this:
$other_user = ($msg_to == $username) ? $msg_from : $msg_to;
And full code will be like this:
<?php
$displayed = [];
// get number of messages from a specific user to the logged in user
$get_mess = mysqli_query ($connect, "SELECT * FROM private_messages ".
"WHERE message_to = '$username' AND message_from ='$user'");
$num_msgs = mysqli_num_rows($get_mess);
// getting all the conversations which concern the user logged on.
$con = mysqli_query ($connect, "SELECT * FROM private_messages ".
"WHERE message_from='$username' OR message_to='$username'");
while ($get_con = mysqli_fetch_assoc($con)){
$msg_from = $get_con['message_from'];
$msg_to = $get_con['message_to'];
$other_user = ($msg_to == $username) ? $msg_from : $msg_to;
// get other persons firstname
$u_name = mysqli_query($connect, "SELECT * FROM users ".
"WHERE username ='$other_user'");
$get_cu = mysqli_fetch_assoc($u_name);
$got_ufn = $get_cu['first_name'];
$got_uln = $get_cu['last_name'];
if ($msg_to == $username || $msg_from == $username){
if(!in_array($other_user, $displayed)) {
echo "<li class='list' role='presentation'>
<div class='parent'>
<div class='disp_pic'>
<img class='img-rounded' src='$profile_pic2'/>
</div>
<div class='user_d'>
<a href='messages.php?u=$other_user'> $got_ufn $got_uln</a>
</div>";
if ($num_msgs == 0){
// dont display badge
}else {
echo "<span id='num_of_msgs_from' class='badge'>";
if ($user == $user){
$num_msgs == 0;
echo "$num_msgs </span>";
}else {
echo " $num_msgs </span>";
}
}
echo"
</div>
</li>";
$displayed[] = $other_user;
}
}
} // while closed
?>

While in Mysql Only Pulls the last result?

I got this simple script , unfortunately It has a issue , its only pulling the last result of the table called site where its supposed to replace badwords/bannedwords/smiles , here's the system That I've made, thanks!
<?php
$select=mysql_query("SELECT * FROM chat ORDER BY id DESC");
while($rows=mysql_fetch_assoc($select)) {
$mid=$rows['id'];
$name=$rows['name'];
$text=$rows['message'];
$date=$rows['date'];
$sitechoose = mysql_query("SELECT * FROM site");
while($change = mysql_fetch_assoc($sitechoose)){
$o = array($change['original'],);
$r = array($change['changed'],);
$messages = str_replace($o, $r, $text);
}
echo "<div class='chat-content'>
<div class='background chat-title'>
<a href='user.php?id=".$name."'>
<span class='user-name user-group-".$power."'>".$name."</span>
</a>
<div class='chat-date float-r'>
<time datetime='2014-12-06T16:56:36+00:00'>".$date."</time>
</div>
</div>
<div class='chat-message'>".$messages."</div>
</div>";
}
?>
It is only pulling out the last result inserted in the site table , I wonder why and how can I fix it?
After looking what the problem was we finally found it :)
<?php
$select = mysql_query("SELECT * FROM chat ORDER BY id DESC");
while($rows=mysql_fetch_assoc($select)) {
$mid=$rows['id'];
$name=$rows['name'];
$text=$rows['message'];
$date=$rows['date'];
$sitechoose = mysql_query("SELECT * FROM site");
while($change = mysql_fetch_assoc($sitechoose)) {
$o = $change['original'];
$r = $change['changed'];
$text = str_replace($o, $r, $text);
}
echo "<div class='chat-content'><div class='background chat-title'><a href='user.php?id=".$name."'><span class='user-name user-group-".$power."'>".$name."</span></a><div class='chat-date float-r'><time datetime='2014-12-06T16:56:36+00:00'>".$date."</time></div></div><div class='chat-message'>".$text."</div></div>";
}
?>

IF statement will not work

I am trying to grab favorite posts from 'posts_fav' where the post id is of the row id. Then i want it to if the userid on the query equals the members id it will show 'yes' otherwise it will show 'No'.
Originial:
foreach ($usersfav as $rowfav) {
if ($rowfav["user_id"] == $member["id"])
{
echo 'yes';
}
else
{
echo 'no';
}
}
One of my attempts:
This changes all to the else function. Skips the check of the if as there needs to be a way I can get $rowfav[""] without needing
foreach ($usersfav as $rowfav) {
$sqlfav = "SELECT * FROM posts_fav WHERE post_id = '".$row["id"]."'";
$stmfav = $dbh->prepare($sqlfav);
$stmfav->execute();
$usersfav = $stmfav->fetchAll();
if ($rowfav["user_id"] == $member["id"])
{
echo 'yes';
}
else
{
echo 'no';
}
}
Update:
So I want the posts where rowfav["user_id"] and member["id"] match up to say 'Yes' and other posts without any rows that can be found to say 'no'
Full code:
$sql = "
SELECT *,
(SELECT profilepic FROM users WHERE users.username = users_profiles_comments.author) AS profilepic
FROM users_profiles_comments WHERE postid = '". $row["username"] ."' ORDER BY `id` DESC";
$stm = $dbh->prepare($sql);
$stm->execute();
$users = $stm->fetchAll();
foreach ($users as $row) {
echo ' <div class="row user-row">
<div class="col-xs-3 col-sm-2 col-md-2 col-lg-2">
<img class="img-thumbnail"
src="'.$row['profilepic'].'" width="150px;"
alt="User Pic">
</div>
<div class="col-xs-10 col-sm-10 col-md-10 col-lg-10">
<div class="panel panel-default">
<div class="panel-heading"><b>'. $row["author"] .'</b> - <small>'. $row["date"] .'</small>
';
if ($row["author"]) {
echo '<p style="float:right;">';
$sqlfav = "SELECT * FROM posts_fav WHERE post_id = '".$row["id"]."'";
$stmfav = $dbh->prepare($sqlfav);
$stmfav->execute();
$usersfav = $stmfav->fetchAll();
foreach ($usersfav as $rowfav) {
if (strcmp($rowfav["user_id"], $member["id"]) == 0)
{
echo '
Yes
';
}
else {
echo 'No';
} }
if (count($usersfav)!=0)
{
foreach ($usersfav as $rowfav)
{
if (strcmp($rowfav["user_id"], $member["id"]) == 0)
{
echo 'Yes';
}
}
}
else
{
echo 'No';
}
If I understood it right, you want to get the favourite posts of a user, and with that, get the information that it's his post or not.
You could, as a suggestion, let the check be done on the query, so your results would come already with the flag you want.
$sql = "SELECT posts_fav.*, posts.*, IF(posts.user_id = ?, 1, 0) as owns_post FROM posts_fav LEFT JOIN posts ON posts_fav.post_id = posts.id WHERE posts_fav.member_id = ?";
$query = $dbh->prepare($sql);
$query->bind_param("posts_member_id", $member["id"]);
$query->bind_param("member_id", $member["id"]);
$query->execute();
$rows = $query->fetchAll();
foreach($rows as $row) {
if($row["owns_post"]) {
echo "User owns the post";
} else {
echo "User does not own the post";
}
}
Not tested, no garantee that it even works. :-)

Unique URL for each MySQL query

I have the below code and cant make it work to save my life. It just needs to have one of 3 links depending on which department it is from. If department = 1 then URL1.com and so on.
<?php
// Make a MySQL Connection
mysql_connect("localhost","dfasrgasdg","asdgasdgasdg") or die(mysql_error());
mysql_select_db("asdgasdgash") or die(mysql_error());
// Get all the data from the "example" table
$album = mysql_query("SELECT * FROM gallery_albums WHERE draft = 0 ORDER BY gallery_id DESC
LIMIT 0,3")
or die(mysql_error());
while($album1 = mysql_fetch_array( $album )) {
if ($album1['department_id'] == '1'); {
$albumURL = "http://ufire.sabinalcanyon.org/gallery.php?gallery_id=".$album1['gallery_id'];
}
if ($album1['department_id'] == '2'); {
$albumURL = "http://ems.sabinalcanyon.org/gallery.php?gallery_id=".$album1['gallery_id'];
}
if ($album1['department_id'] == '3'); {
$albumURL = "http://vfire.sabinalcanyon.org/gallery.php?gallery_id=".$album1['gallery_id'];
}
echo "
<li class=\"clearfix\">
<a href=\"".$albumURL."\" class=\"thumbnail\">
<img src=\"".$album1['poster_image']."\" width=\"50\" height=\"50\" alt=\"\" />
</a>
".$album1['title']."
<div class=\"entry-excerpt\">".$album1['desc']."</div>
</li>";
}
?>
u do know that you have a single '=' for comparison when you should have 2?

PHP MySQL Fetch Printing Help

Basically I have two files, group.php and class.Groups.php
I am trying to print out the 20 last messages posted to the group, however I cannot figure it out as I am pretty new to this! Any help welcomed.
The problem I am having is that the function I am calling is inside a class. Just dont know how to do the while loop and printing.
Would also welcome suggestions and feedback on my code structure & layout.
Thanks.
class.Groups.php
<?php include("config.php");
// Get Group Details
class Group {
var $groupID;
var $groupName;
var $groupDescription;
var $groupMessage;
function group_details($ID) {
$group_details = mysql_query("SELECT * FROM Groups WHERE GroupID = '".$ID."' LIMIT 1");
if (mysql_num_rows($group_details) == 1) {
$group_details_row = mysql_fetch_assoc($group_details);
$this->groupID = $group_details_row ['GroupID'];
$this->groupName = $group_details_row ['Name'];
$this->groupDescription = $group_details_row ['Description'];
}
}
function group_member($ID) {
$group_member = mysql_query("SELECT * FROM GroupMembers WHERE GroupID = '".$ID."' AND UserID = '".$_SESSION['UserID']."' LIMIT 1");
if (mysql_num_rows($group_member) == 1) {
return 1;
}
else {
return null;
}
}
function group_messages($ID) {
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$this->groupMessage = $group_messages_row['Message'];
}
}
}
?>
group.php
<?php include("includes/class.Groups.php");
$group = new Group;
$group->group_details($_GET['ID']);
if ($_SESSION['LoggedIn'] == 1) {
if ($group->group_member($_GET['ID'])) {
include("includes/header.php"); ?>
<div id="container">
<div id="menu"><?php include("includes/sidebar.php"); ?></div>
<div id="main">
<h2><?php echo $group->groupName; ?></h2>
<p><?php echo $group->groupDescription; ?></p>
<h3>Messages</h3>
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage;
}
?>
</div>
</div>
<?php
}
else {
echo "You are not member of this group.";
}
}
?>
You cannot use $group->group_messages() inside a while, because:
It doesn't return anything (return evaluates to false)
It goes through all the rows in one call, while you are expecting it to return one row at a time
You can rewrite your class code to collect all rows in a variable, return it and the iterate on it using foreach loop
// class.Groups.php
function group_messages($ID) {
$group_messages = array();
$group_messages = mysql_query("SELECT * FROM GroupMessages INNER JOIN Users ON Users.UserID = GroupMessages.UserID WHERE GroupID = '".$ID."' LIMIT 20");
while ($group_messages_row = mysql_fetch_assoc($group_messages)) {
$group_messages[] = $group_messages_row['Message'];
}
return $group_messages;
}
// groups.php
<h3>Messages</h3>
<?php
foreach ($group->group_messages($_GET['ID']) as $group_message) {
echo $group_message;
}
?>
You seem to have an extra curly brace in this chuck of code:
<?php
while ($group->group_messages($_GET['ID'])) {
echo $group->groupMessage; }
} ?>

Categories