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
}
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.
This question already has answers here:
How can I get an unknown username given an ID?
(2 answers)
Closed 1 year ago.
am new here, i have an issue with displaying logged in user profile, hoping you guys can help, here is my code :
<?php session_start(); include 'dpconfig.php'
<?php $run = mysqli_query($conn,"Select * from user Where id = $_SESSION['uid]");
$row = mysqli_fetch_array($run, MYSQLI_BOTH); { }
$showid = $row[0];
$showfirst = $row[1];
$showlast = $row[2];
$showuid = $row[3];
echo $showid; echo $showfirst; echo $showlast; echo $showuid;
Now basically this code gives me the details of the first id in my database even if i login different users, i need help selecting data from table name(user) to display logged in user profile, using sessions. Thanks
$run = mysqli_query($conn,"Select * from user where username='xxx' and pass='xx'");
it will return login user detail.
Try something like this, you need to remember to check that the array holds values as well, then you can respond to it...
$conn = dbconfig;
$id = $_SESSION['id'];
$sql = "SELECT * FROM user WHERE id='$id'";
$check = mysqli_query($conn, $sql) or die ("err $id " . mysqli_error ($conn));
$check2 = mysqli_num_rows($check);
if ($check2 != 0) {
while ($row = mysqli_fetch_assoc($check)) {
$userid = $row['id']; // repeat for all db columns you want
}
}
Sorry if there are any typos, done this on my phone quickly. If you need further help gimme a shout.
Updated the code to show more information with the error message, to help you get to the bottom of why it's not working for you.
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 have a pretty simple thing going here. Basic query, but I threw a curve at myself when I decided to go one step further.
Basically it goes like this:
Check if the user entered a value in the form
If not, kick out and display a basic error
If they did then check that value against the database to make sure it is valid/exists
If it's valid/exists, set a session variable and go the order form
If not, kick out and display a basic error
What I want to do now is add another check in there, if the user id exists, then I need to check the order status, if they have already order then I want to kick out and Display a simple message letting them know they have already placed the order and it is being processed. If they have not already ordered then I want to proceed to the order form as above.
The database has a field called "ordered" which has a 1 if they have ordered and a 0 if they haven't ordered yet.
Here is my code that is working, I have tried several things but it keeps blowing up:
<?php
session_start();
$db_host = 'localhost';
$db_username = 'xxxxxx';
$db_password = 'xxxxxxxx';
$db_name = 'xxxxxxxx';
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
/** Check whether the user has filled in the text field "employee_id" */
if ($_POST['employee_id'] == "") {
$IdIsEmpty = true;
}else{
$employee_id = $_POST['employee_id'];
if(mysql_num_rows(mysql_query("SELECT employee_id FROM TABLE_2 WHERE employee_id = '$employee_id'"))){
// if userid exists
$_SESSION['emp_id'] = $employee_id;
header('Location: orderform.php');
exit;
}
$IdNotFound = true;
}
}?>
<head>
</head>
<body>
<b>Please enter your Employee ID: </b><br><br>
<form class="" action="index.php" method="post" enctype=
"multipart/form-data" name="test_form" id="test" accept-charset=
"utf-8"><input type="text" name="employee_id">
<?php
/** Display error messages if "employee_id" field is empty or if ID does not exist */
if ($IdIsEmpty) {
echo ("<br>");
echo ("<b>Enter your employee ID, please!</b>");
echo ("<br>");
}?>
<?php
/** Display error messages if "employee_id" field is empty or if ID does not exist */
if ($IdNotFound) {
echo ("<br>");
echo ("<b>Your employee ID not found!</b>");
echo ("<br>");
}?>
<input type="submit" value="Submit">
</form>
</body>
</html>
Besides swapping out mysql_ functions for mysqli_ like Shivan suggested, you should do this:
Escape any input - you can never trust data provided by users, so do
$employee_id = mysql_real_escape_string($_POST['employee_id']);
In case it is a number, you could also do
$employee_id = intval($_POST['employee_id']);
Just keep this in mind whenever you use input.
Now for your problem:
Simply select your ordered field in the same query:
$order_qry = mysql_query("
SELECT employee_id, ordered
FROM TABLE_2 WHERE employee_id = '$employee_id'
");
if(mysql_num_rows($order_qry)) {
$order = mysql_fetch_object($order_qry);
if( ! $order->ordered) { // If not ordered
// ... do something
} else { // If already ordered
// ... tell the client
}
} else {
// No record found ... error message here
}
I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.