i have a profile page that contain a comment system and i just allow the owner of the profile to write their comments now i want to allow friends also to write how to do that ???
in the members table i have a friend_array field that contain the ids of users that are friend with this user
the friend request system include ajax and jquery
code.php
$blab_form="";
if(isset($_SESSION['user_id']))
{
if($_SESSION['user_id']==$id)
{
$blab_form='
'.$blab_output_msg.'<br />
<div style="background-color:#D2F0D3;border:#999 1px solid; padding:8px;">
<form action="profile.php" method="post" enctype="multipart/form-data" name="blab_form">
<textarea name="blab_field" cols="" rows="4" style="width:100%;">
</textarea><br />
(220 Char Max)
<input type="submit" name="submit" value="Blab"/>
</form></div>';
//$sql = mysql_query("DELETE FROM blabing WHERE u_id ='$id'")or die(mysql_error());
}
}
friend_request_system
<?php
//****************friend request system********************//
// for securing the request with and encryption to be more secure.
if(isset($_SESSION['wpit']))
{
$_SESSION['wipt'];
}
$theRundomNum = rand(99999999999999,9999999999999);
$_SESSION['wipt'] = base64_encode($theRundomNum);
//*********for distinguich the users*************//
//if member is a viewer
$friendLink = "";
if(isset($_SESSION['user_id'])&&$_SESSION['user_id']!=$id)
{
//for quering friend array for the viewer if he is not the owner
$sqlArray = mysql_query("SELECT friend_array FROM members WHERE user_id ='".$_SESSION['user_id']."' LIMIT 1")or die(mysql_error());
while($row = mysql_fetch_array($sqlArray))
{
$iFriendArray = $row['friend_array'];
}
$iFriendArray = explode("," , $iFriendArray);
if(in_array($id, $iFriendArray))
{
$friendLink = 'Remove Friend';
}
else
{
$friendLink = 'Add as Friend';
}
$interactionBox='<div class="interactionLinksDiv">
'.$friendLink.'
</div>';
}
//if member is the profile ower
else
{
$interactionBox = '<div class="interactionLinksDiv">
Freind Request List </div>';
}
?>
if($_SESSION['user_id']==$id) is specific to the blog owner, right? So you make this conditional check if the session id is in an array of acceptable id's. Something like this:
// assuming you already populated the $iFriendArray as outlined in your question
$iFriendArray[] = $id; // add blog owner to the friend array
if(in_array($_SESSION['user_id'], $iFriendArray))
{
// can comment
}
This has been updated to use the friend array as updated in your question.
Any questions feel free to ask and I may update.
Related
I'm currently working on a school project to create a quiz program (local-host) to assess students based on their marks on the quiz. So in that project's database, I have a "student" table and also a "student_name" table. I would have put it in the same table but my teacher told me to put it into two different tables as a normalization step to reach 3nf (getting rid of "transitional functions")? Below are the pictures of my tables: (Sorry, it's in Malay)
"murid"(student) table <no_kp_murid = "student's IC number"> <katalaluan = "password">
"nama_murid"(student_name) table <email_murid = "student's email"> <nama_murid = 'student's name>
So the problem is in the login page. Currently I'm using a "no_kp_murid"(IC number) - "katalaluan"(password) combination to log-in. So it logs in fine, but in the main_menu I'd like to display the "nama_murid"(student's name) attribute. The problem is, it displays the first student name registered and not the actual student-that-logged-in's name. Here's my code:
<?php
session_start();
include ('sambungan.php');
if (isset($_POST['no_kp']))
{
$no_kp = $_POST['no_kp'];
$katalaluan = $_POST['katalaluan'];
$sql_nama_murid = 'select * from nama_murid';
$return = mysqli_query($sambungan , $sql_nama_murid);
$nama_murid = mysqli_fetch_array($return); // isytihar $nama_murid sbg pewakil table nama_murid
$sql_murid = 'select * from murid';
$result = mysqli_query($sambungan , $sql_murid);
$jumpa = FALSE;
while($murid = mysqli_fetch_array($result))
{
if($murid['no_kp_murid'] == $no_kp && $murid['katalaluan'] == $katalaluan)
{
$jumpa = TRUE;
$_SESSION['username'] = $no_kp;
$_SESSION['nama_murid'] = $nama_murid['nama_murid'];//this'd be where the error is
$_SESSION['status'] = 'murid';
header('Location: utama_murid.php');
break;
}
}
if($jumpa == FALSE)
{
$sql_guru = "select * from guru";
$result = mysqli_query($sambungan , $sql_guru);
while($guru = mysqli_fetch_array($result))
{
if($guru['no_kp_guru'] == $no_kp && $guru['katalaluan'] == $katalaluan)
{
$jumpa = TRUE;
$_SESSION['username'] = $guru['no_kp_guru'];
$_SESSION['nama_guru'] = $guru['nama_guru'];
$_SESSION['status'] = 'guru';
header('Location: utama_guru.php');
break;
}
}
}
else
echo "<script>alert('Kesalahan pada username atau password');
window.location = 'login.php'</script> ";
}?>
<title>Kuizrep - Log Masuk</title>
<link rel='stylesheet' href='form.css'>
<body>
<div class="login">
<img src="Logo%20Kuizrep.png" />
<form class='login' action = 'login.php' method = 'post'>
<input class="input" type="text" placeholder="no kad pengenalan" required = '' name = 'no_kp'/>
<input class="input" type="password" placeholder="katalaluan" required = '' name = 'katalaluan' />
<br>
<br>
<br>
<button class = 'butang' type="submit"> Login </button>
</form>
<br>
<centre>Pengguna Baharu?</centre>
</div>
Any suggeesion's on what log-in credential combination I could use? I thought of putting the primary key of "murid"(student) table into the "nama_murid"(student's name) table so that I could use WHERE on he SQL query for calling the student's name but then I'd have to mess up my relationships and then I'd have to alter my other php codes in signup page etc. I'd really not have to do that. Any easier alternatives? Oh yeah, I code using html, and php and myphpadmin server. So no js pls. If you want any translations you can ask me I'll translate them.
"P.S: Sorry everything's in Malay and sorry if my code's messy. I'm a newbie"
There are a few errors that I found in your code. First of all, the student name table (nama_murid) needs to have a foreign key. In this case, the nama_murid table needs to have student_id similar to the murid table.
Your new nama_murid table should look like this:-
no_kp_murid (Student Id) ---- email_murid (Student email) ---- nama_murid (Student Name)
Here no_kp_murid is the foreign key that would relate the student login table to the student name table.
Regarding the code, there is an easier way to achieve what you want.
<?php
session_start();
include ('sambungan.php');
if(isset($_POST['no_kp']){
$no_kp = $_POST['no_kp'];
$katalaluan = $_POST['katalaluan'];
$query = "select * from nama_murid where no_kp_murid='".$no_kp."' && katalaluan='".$katalaluan."'";
$result = mysqli_query($sambungan , $query);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_assoc($result)) {
$jumpa = TRUE;
$_SESSION['username'] = $no_kp;
$query_new = "select * from nama_murid where no_kp_murid ='".$no_kp."'";
$result_new = mysqli_query($sambungan , $query_new);
if ($result_new->num_rows > 0) {
while($row_new = mysqli_fetch_assoc($result_new)) {
$_SESSION['nama_murid'] = $row_new['nama_murid'];
}
}
$_SESSION['status'] = 'murid';
header('Location: utama_murid.php');
break;
}
}
}
?>
You can either edit the rest of the code to follow a similar style or leave it as it is.
I am having a problem keeping the state of some image buttons after refresh or log out. I have a favourite button on each article on page that a user can click to favourite it. I use the following jquery function to send the unique id of the post to a mysql table:
$('.faver').on('click',function() {
var articleId = $(this).closest('.row').attr('id');
$.ajax(
{
url: "favscript/addremove",
method: "POST",
data: { favourite: articleId },
success: function()
{
alert(<?php echo $favid ?>);
}
});
});
then in the recieving php file i get the session variable like this:
session_start();
if(isset($_SESSION['id']) AND isset($_POST['favourite'])){
$user = mysql_real_escape_string($_SESSION['id']);
$_SESSION['favourite'] = $_POST['favourite'];
$favid = mysql_real_escape_string($_SESSION['favourite']);
and then I insert values into mysql table like so:
// Firstly, check if article is favourite or not
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user=$user AND favid=$favid");
$matches = mysql_num_rows($query);
// If it is not favourited, add as favourite
if($matches == '0'){
mysql_query("INSERT INTO ajaxfavourites (user, favid) VALUES ('$user', '$favid')");
}
// Instead, if it is favourited, then remove from favourites
if($matches != '0'){
mysql_query("DELETE FROM ajaxfavourites WHERE user=$user AND favid=$favid");
}
}
Now all of the above is working but my problem is that I can't seem to figure out a way for each button to remember its state once the user refreshes or logs out. if I set $favid to $_SESSION['favourite'] it will just set the button state the same for all buttons after refresh.
this is how i check what the button state should be:
<!--Favourite Button-->
<div id="favouritediv">
<?php
$user = $_SESSION['id'];
$favid = $_SESSION['favourite']; // <- problem here
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE user=$user AND favid=$favid");
$matches = mysql_num_rows($query);
if($matches == 0){
?>
<img id="button" class="faver fave0 tog" src= "favscript/images/0.jpg" onclick="" width="54" height="49">
<?php
}
if ($matches == 1) {
?>
<img id="button" class="faver fave0 tog" src= "favscript/images/1.jpg" onclick="" width="54" height="49">
<?php
}
?>
</div>
<!--Favourite Button END-->
if i set $favid to the id of the article directly like: $favid = 3; it will work perfect but I can't get my head around how to do it properly with a $session variable or something that will get the article id for each button separately and only effect each button by itself.
I hope this makes sense, I am new to php and any help on how I should do this will be much appreciated.
thanks.
If you want sessions even after user logged out , simply Store login activities in separate table. like columns User ID and Session IDs. finally get the last row of the activity table.
Happy coding !
I think your query should be to fetch all the favids for a user:
$query = mysql_query("SELECT favid FROM ajaxfavourites WHERE user=$user");
while($row = mysql_fetch_assoc($result)){
$allFavIds[] = $row['favid'];
}
Now using $allFavIds array you can check for each button if its "favid" exists in this array.
<img id="button" class="faver fave0 tog" src="favscript/images/<?php echo in_array($individualFavId, $allFavIds) ? '1.jpg' : '0.jpg' ; ?>" onclick="" width="54" height="49">
Of-course the $individualFavId will be replaced by your individual favids.
Sample Code:
<img id="button" class="faver fave0 tog" src="favscript/images/<?php echo in_array(3, $allFavIds) ? '1.jpg' : '0.jpg' ; ?>" onclick="" width="54" height="49">
I'm making a site similar to Instagram. I am very new to php. I created a follow button in the user's profile.
How do you make the follow button disappear when you already followed the user?
How do you replace it with unfollow button?
// my php code for following
if (isset($_POST['addfriend'])){
$fromuser = $user;
$touser = $username;
if($fromuser == $username){
$Msg = "You cannot follow yourself<br/>";
}
else
{
$getID= mysql_query("SELECT userID FROM user WHERE username='$user'");
$get_ID_row = mysql_fetch_assoc($getID);
$ID_db = $get_ID_row['userID'];
$sql = "insert into following (userID, fromUser, toUser)
values ('$ID_db','$fromuser', '$touser')";
$result = mysql_query($sql);
$Msg= "Success! <br/>";
}
}
else{
//Do nothing
}
//my code for the follow button
<form action="<?php $user;?>" method ="POST">
<?php echo $Msg; ?>
<input type = "submit" name ="addfriend" value = "Follow"/>
</form>
On the page where you are going to show the Follow or Unfollow button, first run a MySQL query to find out if you are already following the person:
$sql = "select * from following
where userID = $user
and fromUser = $fromUser
and toUser = $toUser";
$result = mysql_query($sql);
if( $result) {
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
....[see below]
Now dynamically create whichever button you need:-
if( mysql_num_rows($result) > 0) {
// if we get here we know we are already following that person
echo '<input type = "submit" name ="removefriend" value = "Un-follow"/>';
}
else
{
echo '<input type = "submit" name ="addfriend" value = "Follow"/>';
}
And on the following page where you are getting the form results, check for both buttons:
if (isset($_POST['addfriend'])) {
...[do what you already have]
}
else
if (isset($_POST['removefriend'])) {
...[do SQL to remove the record from the following table]
}
Please be aware also that as of PHP v5.5 this style of MySQL is deprecated. At some stage in the future you will have to convert your programs to the MySQLi or PDO_MySQL extensions, before they eventually discontinue support. See the PHP manual about this at eg http://php.net/manual/en/mysqlinfo.api.choosing.php.
Would be easier with OO PHP. However, if you chose procedural, let's assume we have a table of friends. Which keeps the id of each of my friends.
e.g.: Smith follows John
Then you do something like
$following = mysql_query("SELECT COUNT(*) FROM followers WHERE followerid = ".$_SESSION['id']." AND followeeid = ".$username);
Check if You follow the person already:
if($following){//$following == true
}
This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.
I am trying to check if a user is the owner of a profile page so that i can display a text box for entering twitter similar posts.
The code
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$ultimatum_form ='';
if(isset($_SESSION['id'])){
if($_SESSION['id']==$id){
$ultimatum_form = 'Write an ultimatum!(220 char max)<br/>
<form action="profile.php" method="post" enctype="multipart/form-data" name="ultimatum_form">
<textarea name="ultimatum_field" rows="3" style="width:97%;"></textarea>
</form>';
}
}
print "$ultimatum_form";
in my DB i have a table called "users", the table users has the columns "firs", "last", "username", "password", "email" and "id".
If i set $ultimatum_form outside of the session check it outputs the text-field and it works. The problem is that if i then go to another persons profile i can see the text-field and write posts for them.
You need to get data from the query:
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$r = mysql_fetch_assoc($id);
$id = $r['id'];
then $id contains the row "id" value.
look into pdo/mysqli, mysql won't wrok in next php version.
here, better:
$id=mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'");
$r = mysql_fetch_assoc($id);
$id = $r['id'];
if(isset($_SESSION['id']))
{
if($_SESSION['id']==$id)
{
echo '
Write an ultimatum!(220 char max)<br/>
<form action="profile.php" method="post" enctype="multipart/form-data" name="ultimatum_form">
<textarea name="ultimatum_field" rows="3" style="width:97%;"></textarea>
</form>';
}
else
{
// Not users profile page
}
}
You can't exactly do what you're doing. You need to fetch the records.
$results = mysql_fetch_array(mysql_query("SELECT id FROM users WHERE`username`='".$_GET['username']."'"));
Then you can do:
if($_SESSION['id']==$results['id']){