How to create if statement inside echo in PHP MySQLi - php

I want to ask,
I have two tables , users and posts with column field
users : user_id, name, email
posts : post_id, user_id, post_title
I want to display all posts from all users,
but I want only logged_in user session to have another two extra button while other public posts only have two button
p/s : I used email column field in users table as login $_SESSION.
<?php
global $connect;
global $user_id;
$sql_post = "SELECT * FROM posts";
$run_post = mysqli_query($connect, $sql_post);
if($run_post && mysqli_num_rows($run_post) > 0 )
{
while($row_post = mysqli_fetch_array($run_post))
{
$post_id = $row_post['post_id'];
$user_id = $row_post['user_id'];
$post_title = $row_post['post_title'];
$sql_user = "SELECT * FROM users WHERE user_id='$user_id'";
$run_user = mysqli_query($connect, $sql_user);
$check_user = mysqli_fetch_array($run_user);
$user_id = $check_user['user_id'];
$user_name = $check_user['name'];
$user_email = $check_user['email'];
$post_output = "<div id='posts_wrap'>
<p>$user_name</p>
<p>$user_email</p>
<p>$post_title</p>
<a href=''><button>Like</button></a>
<a href=''><button>Comment</button></a>
// i want these two button (Edit and Delete) only available to logged in user
<a href=''><button>Edit</button></a>
<a href=''><button>Delete</button></a>
</div>
";
echo $post_output;
}
mysqli_free_result($run_post);
}
else
{
echo "No post yet";
}
?>

After user loggine keep user detail in session and check condition if user logged in or not For example if you are trying to comment and like only for logged in user then you can do somethink like
<?php
session_start();
$_SESSION['email']='email#example.com';
$user_name='dd';
$user_email='ddd';
$post_title='gsdg';
$post_output = "<div id='posts_wrap'><p>$user_name</p><p>$user_email</p><p>$post_title</p>";
if(isset($_SESSION['email'])){
$post_output.="<a href=''><button>Like</button></a><a href=''><button>Comment</button></a> ";
}
// i want these two button (Edit and Delete) only available to logged in user
$post_output.= "<a href=''><button>Edit</button></a><a href=''><button>Delete</button></a> </div>";
print_r($post_output);
?>
in the above code user is logged in so all buttons are visible .if not then its not visible to all .just try to destroy session.i think previous session email still there

i found the solutions . it turns out that i need to create another query and combine the user_id and email to makesure the login is belong to the loggedin user. here's the code
<?php
global $connect;
global $user_id;
$get_post = "SELECT * FROM posts";
$run_post = mysqli_query($connect, $get_post);
if($run_post && mysqli_num_rows($run_post) > 0 )
{
while($row_post = mysqli_fetch_array($run_post))
{
$post_id = $row_post['post_id'];
$user_id = $row_post['user_id'];
$post_title = $row_post['post_title'];
$emailsql = $_SESSION['email'];
$get_email = "SELECT * FROM users WHERE user_id='$user_id' AND email='$emailsql'";
$run_email = mysqli_query($connect, $get_email);
$check_email = mysqli_fetch_array($run_email);
$d_email = $check_email['email'];
$get_user = "SELECT * FROM users WHERE user_id='$user_id'";
$run_user = mysqli_query($connect, $get_user);
$check_user = mysqli_fetch_array($run_user);
$user_id = $check_user['user_id'];
$user_name = $check_user['name'];
echo "<div id='posts_wrap'>
<p><h3><a href='userprofile.php?user_id=$user_id'>$user_name</a></h3></p>
<div id='posts_title'>
<p><h3><a href='post.php?post_id=$post_id'>$post_title</a></h3></p>
</div>
<hr>
<a href=''><button>Like</button></a>
<a href=''><button>Comment</button></a>
";
if($check_email){
echo "
<a href=''><button>Edit</button></a>
<a href=''><button>Delete</button></a>";
}
echo "</div>";
}
mysqli_free_result($run_post);
}
else
{
echo "No post yet";
}
?>

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
?>

PHP if in POST load only the first if

I have this code :
if(isset($_POST['remove'])){
$con = mysqli_connect(".","","","");
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
It is working, but I want it to do something like this
if(isset($_POST['remove'])){
$con = mysqli_connect("","","","");
while($row = mysqli_fetch_assoc($q)){
if($row['picture'] == ""){
echo "<div class='notemarg'> No pictures to delete</div>";
} else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
}
This means that the picture from database will be removed only if there IS any picture.. if not, then it will display that message "No pictures to delete" ... but it does not work.. it still shows that error message that there is no picture even though there is no blank row in database and so it does not delete the information in row either...
Where is problem?
BTW: first code works fine... and it works even if there is nothing in database so it kinda does not make sense that the "profile picture has been removed." is being displayed...
Try this instead:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con, "SELECT picutre FROM members where username = '". $_SESSION['username']. "'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}
You need the mysqli_query statement:
$con = mysqli_connect("","","","");
if(isset($_POST['remove'])){
$q = mysqli_query($con,"SELECT IFNULL(picture,'') AS picture
FROM members
WHERE username = '".$_SESSION['username']."'");
$row = mysqli_fetch_assoc($q);
if( empty($row['picture'])){
echo "<div class='notemarg'> No pictures to delete</div>";
}
else {
$q = mysqli_query($con,"UPDATE members SET picture = '' WHERE username = '".$_SESSION['username']."'");
header( "refresh:2;url=settings.php" );
echo "<div class='notemarg'>Profile Picture has been removed. Refreshing page within 3 seconds...</div>";
}
}

validation php not working?

The following is the email verification code for my site.
The verification url sent to the user's email is as follows:
http://www.mywebsite.com/valid.php?confr=2774405&userid=2
Extra notes :
1) key is a column in my database which gets a random value on registration.
2) if $verify == 1 and password_in_db=== user_entered_password, then login takes place in the login page.
<?php
include 'connect.php';
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$_GET['userid']'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1") {
echo "Link Expired . Go to our login page :";
} else {
if (isset($_GET["confr"]) && isset($_GET["userid"])) {
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2) {
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$_GET["userid"]' ;");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
} else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Code for connect.php
<?php
mysql_connect("host", "username", "pass"); //connects to the server
mysql_select_db("database_name"); //selects the database
?>
The problem is that it is giving me a blank screen .
i believe the error lies in the sql
when ever i use a "WHERE" statement i always define as a variable, try this
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
also, you have a semi colon in the insert sql
Try this.......
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
while ($details = mysql_fetch_assoc($query)){
$verify = $details['verify'];
$confirm2 = $details['key'];
}
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Note: insert statement has no where - as long as you dont use "insert into select..."
http://dev.mysql.com/doc/refman/5.1/de/insert.html

Can't find the friend's id to store it to the database

I'm really struggling with this now for a while and can't seem to get it working. In members.php (where I show all the registered users) I have a list printed out with a link "ADD TO FRIENDS" next to each user.
I managed, for testing purposes to display each members id well (so it gets the ID) but when I click the link it directs to the friends.php where it seems the fault is in. I don't know how to get that friend's id I clicked on IN THE friends.php file. Please have a look!
members.php
<?php
include 'connect.php';
include 'header.php';
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> to view all the <b>registered</b> members.';
echo '<br/><br/>';
}
else
{
echo '<h2>Registered users:</h2>';
$sql = "SELECT * FROM users ORDER BY user_name ASC";
$result = mysql_query($sql);
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
//$name = mysql_result($result,$i,"user_name");
//$id = mysql_result($result,$i,"user_id");
//$picture = mysql_result($result,$i,"pic_location");
//?friend_id="'. $id .'
while($user = mysql_fetch_array($result)){
echo $user['user_name'].'<br/><br/>ADD TO FRIENDS<br/>';
echo $user['user_id'];
echo '<br/><br/>';
}
$i++;
}
///////////////////////////////
/// adding users as friends ///
///////////////////////////////
//while($user = mysql_fetch_array($result))
//echo $user['user_name'].'
//ADD TO FRIENDS<br/>';
//NOW I WANT TO MAKE A SPECIFIC "ADD AS FRIEND" LINK NEXT TO EACH USER
}
include 'footer.php';
?>
As I said I'm not sure how to get this so please have a look! Thanks!
J
friends.php
<?php
include "connect.php";
include "header.php";
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> if you want to add the person as a friend!';
echo '<br/><br/>';
}
else
{
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
//friend_id is the ID of the friend that is clicked on...
//HOW DO I GET THAT ID THAT IS CLICKED ON IN THE WHILE "loop" in members.php?
$friends = ("INSERT INTO friends SET user_id='" . $_SESSION['user_id'] . "', friend_id='".$id."', status='0'");
$result_friends = mysql_query($friends);
if(!$friends)
{
//When you can't add this person as a friend this error will show!
echo 'You cannot add this user at this time. Please try again later!';
}
else
{
//When the friend is now added to the system!
echo 'Great! Now the user needs to approve before you can be friends!';
}
}
?>
On your friends.php use
$_GET['user_id']
Instead of $id, $id is undefined, to get the value of id from the query string you call it using an $_GET variable like,
$_GET['name_of_query_string_value']

PHP setcookie is adding Percent Signs

So, I have a simple script that allows you to choose between any of your "team names". When you choose and sumbit, it is then supposed to do a php setcookie with the value of the selection which is a hashed version of the team name.
Here is the relevant code:
<?php
include 'include/db.php';
if(isset($_POST['submitteam'])) {
$team_hash = $_POST['teams'];
setcookie('ver_aet', $team_hash, time()+2592000);
header('Location: index.php');
}
$email = $_COOKIE['ver_ame'];
//Find the User Id from the Email Hash
$sql_finduid = "SELECT * FROM users_sensitive WHERE email_hash = '$email'";
$sql_finduid_result = mysql_query($sql_finduid);
while ($row = mysql_fetch_array($sql_finduid_result)) {
$user_id = $row['user_id'];
} //End Find User Id
/*
$sql_finduid = mysql_query("SELECT user_id FROM users WHERE email = '$email'");
$user_id = mysql_result($sql_finduid) or die(mysql_error());
*/
//Find the Team Id from the User Id above
$sql_findteams = "SELECT * FROM team_members WHERE user_id = '$user_id'";
$sql_findteams_result = mysql_query($sql_findteams);
if(mysql_num_rows($sql_findteams_result) < 1){
header('Location: registerteam.php?ver_ame=' . $email);
} else {
while ($row = mysql_fetch_array($sql_findteams_result)) {
$team_id = $row['team_id'];
/*
$sql_finduid = mysql_query("SELECT user_id FROM users WHERE email = '$email'");
$user_id = mysql_result($sql_finduid) or die(mysql_error());
*/
if((mysql_num_rows($sql_findteams_result)) <= 1) {
$sql_findteamname = "SELECT * FROM teams WHERE team_id = '$team_id'";
$sql_findteamname_result = mysql_query($sql_findteamname);
while ($row = mysql_fetch_array($sql_findteamname_result)) {
$team_name = $row['team_name'];
$team_hash = $row['team_name_hash'];
}
setcookie('ver_aet', $team_hash, time()+2592000);
header('Location: index.php');
} else {
//setcookie('ver_ame', $teamname_hash, time()+2592000);
//setcookie('ver_aet', $email, time()+2592000);
//header('Location: index.php'); ?>
and the HTML
Select the team you would like to view: <br />
<form method="post" action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
<select name="teams">
<?PHP
$sql_findteams = "SELECT * FROM team_members WHERE user_id = '$user_id'";
$sql_findteams_result = mysql_query($sql_findteams);
while ($row = mysql_fetch_array($sql_findteams_result)) {
$team_id = $row['team_id'];
/*
$sql_finduid = mysql_query("SELECT user_id FROM users WHERE email = '$email'");
$user_id = mysql_result($sql_finduid) or die(mysql_error());
*/
$sql_findteamname = "SELECT * FROM teams WHERE team_id = '$team_id'";
$sql_findteamname_result = mysql_query($sql_findteamname);
while ($row = mysql_fetch_array($sql_findteamname_result)) {
$team_name = $row['team_name'] . " ";
$team_hash = $row['team_name_hash'] . "<br />";
?>
<option value="<?= $team_hash; ?>"><?= $team_name . $team_hash; ?></option>
<?PHP
}
}
?>
</select>
<input type="submit" name="submitteam" value="Submit" />
</form>
</div>
</div>
</div>
basically, "if the submit button is clicked, set the cookie for the name of the team. If not clicked, continue. Find the cookie of your email, find out how many teams you belong to, if there is one team, make that your team cookie and continue, if not, show all available teams and allow the user to select one. loop"
I currently have the $team_hash echoing just to show that it is pulling the correct hash number (and it is). When I hit submit, it loops to the top of the page and does the setcookie statement. It sets a cookie but the cookie seems to end up having random percent signs throughout it after it is set.
What should be set: d2fea5c982b6cb3f5bffc4998d96cbe5
What is actually set: d2fea5c982b6cb3f5bffc4998d96cbe5%3Cbr+%2F%3E
Where are these extra things coming from?
The problem is that you're adding <br /> at the end of the hash when you're doing $team_hash = $row['team_name_hash'] . "<br />"; and when you're setting the value of the option, you're using $team_hash which contains a <br />. When you're doing the set cookie, the <br /> gets URL encoded hence why it's at the end of your cookie.
Simple change the line to:
$team_hash = $row['team_name_hash'];
You have a <br/> in there somehow, and PHP is url encoding it.
Right here
$team_hash = $row['team_name_hash'] . "<br />";

Categories