php chat duplicate users prevent - php

i have problem, on my code i create chat, but duplicate users name, i try prevent but not success.... some can help?
my code:
$sql = "SELECT * FROM `inbox` WHERE `from`='".$_SESSION['username']."' OR `to`='".$_SESSION['username']."' ORDER by `data` DESC;";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$lastuser = "";
while($row = mysqli_fetch_array($result)) {
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
if($lastuser != $chat_name) {
echo "
<a href='?user=".$chat_name."'>
<div class='inbox_users_box'>
<div class='inbox_imagenuser'>
<img class='inbox_image' src='".getAvatarOthers($chat_name)."'></img>
<div style='margin-top: 14px; float: left;'>".$chat_name."</div><span style='margin-top: 17px; margin-left: 5px;' class='".getonline_player($chat_name)."'></span>
<div style='clear:both;'></div>
</div>
<div class='inbox_lastmsgdata'>".$row['data']."</div>
</div>
<div style='clear:both;'></div>
</a>
";
$lastuser = $chat_name;
}
}
my chat : my chat picture
i want dont duplicate users..

You can save the filtered inbox entries in an array with the data to display, but only when the user isn't already in that array. This way it gets added only once. After that you print the array the way you like with a normal foreach() loop.
$users = array();
while ($row = mysqli_fetch_assoc($result);
// retrieve the data from MySQL
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
$data = $row['data'];
// look if the user is already in the array
$found = false;
foreach ($users as $user) {
if ($user['name'] == $chat_name) {
$found = true;
break;
}
}
if ($found) {
continue;
}
// its not, so add it
$toAdd = array('name' => $chat_name, 'data' => $data);
$users[] = $toAdd;
}
/* display users */
foreach ($users as $user) {
$username = $user['name'];
$data = $user['data'];
// your HTML code here
}

Related

Setting the result of an if statement

I am displaying a user's profile image. I have created an if statement to post a default profile image if a user has not updated their own. This is all working, but what I cannot figure out is how to echo or call for each without getting an error for the one not set.
For instance, if they do have a profile picture set, it posts fine, but then I get an error that the other variable is not defined and vise versa.
How should I be calling for this or what changes should I make in my code?
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>
EDIT:
How profilepic gets defined:
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("s", $user_id);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);
Just add $default_profile_img = null; and $set_profile_img = null; at the top of php code.
$default_profile_img = null;
$set_profile_img = null;
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if ($profilePic === NULL) {
$default_profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$set_profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $default_profile_img;
echo $set_profile_img; ?>
You just need to initialize the variables before the if..else statements so that it won't be undefined when you try to echo both of them.
$profile_img = "";
$default_profile_img = "";
if (...
Try this code. There is no need to use two different variables. This way, you won't get the warning.
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
if (!isset($profilePic) OR $profilePic === NULL) {
$profile_img = '<img class="welcome-pic" src="profile_images/default.jpg">';
} else {
$profile_img = '<img class="welcome-pic" src=" '.$profilePic.'">';
}
}
?>
<nav id="nav-panel">
<div id="nav-container">
<div id="welcome">
<?php echo $profile_img; ?>

Data not being saved in my database

I hope you are doing great. I'm having a problem where I cannot insert data into my database. There are multiple reasons to why that happens so don't consider it a duplicate question please. I checked my code. For one table it saves the data but for this table. It displays that the same page was not found and no data is saved on the local database. I hope you can help me guys. Thanks in advance. :)
Here are some useful pieces of code:
<?php
include 'Header.php';
?>
<style>
#first {
//margin-right: 100%;
//clear: both;
}
#first > img {
display: inline-block;
//float: left;
}
#first > p {
//float: left;
display: inline-block;
//margin-left: 60px;
//margin-bottom: 120px;
}
</style>
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<!--<?php ?>
if (isset($_GET['id'])) {
$id = $_GET['id'];
} elseif (isset($_POST['id'])) {
$id = $_POST['id'];
} else {
echo '<p class="error"> Error has occured</p>';
include 'footer.html';
exit();
}
$db = new Database();
$dbc = $db->getConnection();
$display = 10; //number of records per page
$pages;
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//use select count() to find the number of users on the DB
$q = "select count(comment_id) from comments";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //calculate the number of pages we will need
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//use LIMIT to specify a range of records to select
// for example LIMIT 11,10 will select the 10 records starting from record 11
$q = "select * from users order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
/*if ($r)
{*/
$result = mysql_query("SELECT * FROM comments WHERE video_id= '" + + "'");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <!--<?php /* echo $row->author; //Or similar in your table ?>
<p>
<?php echo $row->body; ?>
</p>
</div>
<?php
/*} */
?>*/-->
<h1>Leave a comment:</h1>
<form action="Comment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="text" name="comment" value="" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Insert"/>
</form>';
<?php
if (isset($_POST['submitted'])) {
$comment = '';
$errors = array();
if (empty($_POST['comment']))
$errors[] = 'You should enter a comment to be saved';
else
$comment = trim($_POST['comment']);
if (empty($errors)) {
include 'Comments_1.php';
$comment_2 = new Comments();
$errors = $comment_2->isValid();
$comment_2->Comment = trim($_POST['comment']);
$comment_2->UserName = hamed871;
$comment_2->Video_Id = 1;
if ($comment_2->save()) {
echo '<div class="div_1"><div id="div_2">' .
'<h1>Thank you</h1><p> your comment has been'
. ' posted successfully</p></div></div>';
}
}
//First check if everything is filled in
/* if(/*some statements *//* )
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
id (auto incremented)
name
email
text
datetime
approved--> */
}
?>
<!--echo '--><div id="first">
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square" height="42" width="42"/>
<p>hamed1</p>
</div><!--';-->
<dl>
<dt>comment1</dt>
<dd>reply1</dd>
<dd>reply2</dd>
</dl>
<!--//}
/*else
{
}*/
?>-->
<?php
include 'Footer.php';
?>
My Comment class:
<?php
include_once "DBConn.php";
class Comments extends DBConn {
private $tableName = 'Comments';
//attributes to represent table columns
public $comment_Id = 0;
public $Comment;
public $UserName;
public $Video_Id;
public $Date_Time;
public function save() {
if ($this->getDBConnection()) {
//escape any special characters
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
$this->UserName = mysqli_real_escape_string($this->dbc, $this->UserName);
$this->Video_Id = mysqli_real_escape_string($this->dbc, $this->Video_Id);
if ($this->comment_Id == null) {
$q = 'INSERT INTO comments(Comment, User_Id, Video_Id, Date_Time) values' .
"('" . $this->Comment . "','" . $this->User_Id . "','" . $this->Video_Id . "',NOW()')";
} else {
$q = "update Comments set Comment='" . $this->Comment . "', Date_Time='" . NOW() ."'";
}
// $q = "call SaveUser2($this->userId,'$this->firstName','$this->lastName','$this->email','$this->password')";
$r = mysqli_query($this->dbc, $q);
if (!$r) {
$this->displayError($q);
return false;
}
return true;
} else {
echo '<p class="error">Could not connect to database</p>';
return false;
}
return true;
}
//end of function
public function get($video_id) {
if ($this->getDBConnection()) {
$q = "SELECT Comment, Date_Time, UserName FROM Comments WHERE Video='" . $userName."' order by time_stamp";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row = mysqli_fetch_array($r);
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
return true;
}
else
$this->displayError($q);
}
else
echo '<p class="error">Could not connect to database</p>';
return false;
}
public function isValid() {
//declare array to hold any errors messages
$errors = array();
if (empty($this->Comment))
$errors[] = 'You should enter a comment to be saved';
return $errors;
}
}
?>
Output show when I click insert button:
Not Found
The requested URL /IndividualProject/Comment.php was not found on this server.
Apache/2.4.17 (Win64) PHP/5.6.16 Server at localhost Port 80
I encountered this kind of issue when working on a staging site because webhosting may have different kinds of restrictions and strict. Now what I did is changing the filename for example:
Class name should match the filename coz it's case sensitive.
Comment.php
class Comment extends DBConn {
function __construct () {
parent::__construct ();
}
//code here..
}

in php table tag not working

I want the table tag to come before the display of records in cart() function but it is being displayed after it rather?
How to correct that and in cart() function in the display of records when I am trying <tr> and <td> tags to display its not working
<?php
session_start();
$page = 'index.php';
$connection = mysqli_connect("localhost","root","","cart");
if(isset($_GET['add']))
{
if(array_key_exists('cart_'.$_GET['add'], $_SESSION))
$_SESSION['cart_'.$_GET['add']]+= 1;
else
$_SESSION['cart_'.$_GET['add']] = 0;
header("Location: cartindex.php");
}
if(isset($_GET['remove']))
{
$_SESSION['cart_'.$_GET['remove']]--;
header("Location: cartindex.php");
}
if(isset($_GET['delete']))
{
$_SESSION['cart_'.$_GET['delete']]=0;;
header("Location: cartindex.php");
}
function cart()
{
global $connection;
$total = 0;
?>
<table class="table table-striped"><tr><th>ID</th><th>Name </th><th>Price Per Item</th><th>Cost</th><th>Add</th><th>Substract</th><th>Delete</th></tr>
<?php foreach ($_SESSION as $key => $value) {
if($value > 0)
{
$id = substr($key,5,strlen($key)-1);
$result = mysqli_query($connection ,'select id,name,price from products where id ='.$id);
while($row = mysqli_fetch_assoc($result))
{
$cost = $row['price'] * $value;
echo $row['id'].' '.$row['name'].'#'.$row['price'].'*'.$value.'='.$cost.'[+]'.'[-]'.'[delete]'.'<br>';
$total = $total + $cost;
}
}
}
?></table><?php
if($total==0)
{
///
}
else
{
$dis="'payment made'";
echo 'Total cost is '.$total.'<br>';
echo '<br><button type="button" class="btn btn-success" onclick="alert(\'Payment accepted\');">Success</button>';
}
}
function product()
{
$connection = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
die("not connected to db ".mysqli_connect_error());
}
$get = mysqli_query($connection , "select id,name,description,price from products where quantity > 0 order by id DESC");
while($row = mysqli_fetch_assoc($get))
{
echo '<div class="boxed">'.$row['name'].'<br>'.$row['price'].'<br>'.$row['description'].'<br>ADD'.'<br>'.'</div>';
}
}
?>
Try replace "echo" with "return" inside functions.

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. :-)

How do i use php to be able to allow a user to view another users profile

i am creating a social network, when i first created my search bar for names i worked out well but when i click on any name it takes me to the profile of who ever is logged in here is my php code for my search bar
?php
include 'func.inc.php';
if (isset($_POST['full_name'])) {
$first_names = mysql_real_escape_string(htmlentities($_POST['full_name']));
$errors = array();
if (empty($first_names)) {
$errors[] = 'Please enter a search term';
} else if (strlen($first_names)<3) {
$errors[] = 'Your search term must be three or more charecters';
} else if (search_results($first_names) === false) {
$errors[] = 'Your search for '.$first_names.' returned no results';
}
?>
<?php
if (empty($errors)) {
$results = search_results($first_names);
$results_num = count($results);
echo '<div align="center"> <p>Your search for <strong>', $first_names, '</strong> returned <strong>', $results_num, '</strong> results</p> </div>';
foreach($results as $result) {
echo '<h3> <strong> <div align="center"> ', $result['first_name'],' ', $result['last_name'], '<br> ', $result['address'],'</div> </strong> </h3>';
}
}
}
?>
here is func.inc.php
<?php
include 'db.inc.php';
function search_results($first_names) {
$returned_results = array();
$where = "";
$first_names = preg_split('/[\s]+/', $first_names);
$total_first_names = count($first_names);
foreach($first_names as $key=>$first_name) {
$where .= "`full_name` LIKE '%$first_name%'";
if ($first_name != ($total_first_names - 1)) {
$where .= " AND ";
}
}
$results = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE $where";
$results_num = ($results = mysql_query($results)) ? mysql_num_rows($results) : 0;
if ($results_num === 0) {
return false;
} else {
while ($results_row = mysql_fetch_assoc($results)) {
$returned_results[] = array(
'first_name' => $results_row['first_name'],
'last_name' => $results_row['last_name'],
'user_id' => $results_row['user_id']\
);
}
return $returned_results;
}
}
?>
and please explain it in detail im not that good with this email me if anything at philipnagel511#gmail.com

Categories