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.
Related
I've recently finished the PHP course on codeacadamy and I'm currently building my first PHP site. This is my first time coding anything so please forgive the fact that my code might be very unorganized and crude. The site is for a scavenger hunt, and the idea is to have a dedicated page for each item of the hunt. I have two tables in my db that the pages access to check data. I've created a template page, which will basically be called in by each dedicated page. My code is all working as intended. I do, however, get a warning that the $game and $question variables have not been used. I understand why I am getting this warning, and that the solution will probably be to convert the majority of my code in scavenger_template.php into a function and do something like
scavenger_function($game, $question); on my individual pages.
My question is, if I leave the code the way it is, will this potentially cause problems in the long run? Is it better/good practice to functionize as much of the code as possible? If you have any tips for good practices or being efficient in coding, it would be greatly appreciated. Codeacademy doesn't really go into much detail about how to actually go about building something.
Thank you!
(game1.php)~(game00.php) dedicated pages
<?php
$game = 1;
$question = "What is 1+1?";
include 'scavenger_template.php';
?>
(scavenger_template.php)
<?php
session_start();
$username = $_SESSION["username"];
$empty_message = "";
$submission_message = "";
$submission_confirm = "";
$row2 = "";
include ('../db_connection.php');
include ('../addPoints.php');
$conn = OpenCon();
/* define game number for each page. game1 in users correlates to id=1 in games. */
/* declaring variables required to check if game has been submitted */
$sql = "SELECT game$game FROM `users` WHERE username = '$username'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$user_answer = trim(strtolower(($_POST["answer"])));
/*check to see if something is inputed */
if ($user_answer != "") {
/* check if submission is already made. if row = 0, then game hasn't been played */
if ($row[0] === "0") {
/* declaring variables required to check answers in games table */
$sql2 = "SELECT answer FROM `games` WHERE id = '$game'";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_array($result2);
/* check submitted answer against game table */
if ($user_answer === $row2[0]) {
$sql_value = "SELECT value FROM `games` WHERE id = '$game'";
$result_value = mysqli_query($conn, $sql_value);
$row3 = mysqli_fetch_array($result_value);
addPoints($row3[0], $username, $conn);
$sql3 = "UPDATE users SET game$game='1' WHERE username = '$username'";
mysqli_query($conn,$sql3);
$submission_confirm = "Your answer is correct!";
} else {
$submission_confirm = "Your answer is incorrect.";
$sql3 = "UPDATE users SET game$game='1' WHERE username = '$username'";
mysqli_query($conn,$sql3);
}
} else {
$submission_message = "Your team has already made a submission for this item.";
}
} else {
$empty_message = "Please input an answer.";
}
}
?>
<html>
<head>
</head>
<div align="center">
<form method="post">
<label><?= $question ?></label><br>
<input type="text" id="answer" name="answer"><br><br>
<input type="submit" name="submit" value="Submit Answer"><br>
</form>
<?= $submission_message?>
<?= $empty_message?>
<?= $submission_confirm?>
<br><br>
<form action="../home.php">
<input type="submit" value="Go to home" />
</form>
</div>
</html>
I'm currently creating a website where the user can login to an account. For this I need to check if the email and password that has been submitted by the user is the same as those in the MySQL database.
This is my code for this;
<h2> Log in to an existing account </h2>
<form action = "account.php" method = "POST" id = "log">
<p><label> Email </label> <input type = "text" name = "logmail" ></p>
<p><label> Password </label> <input type = "password" name = "logpass"></p>
<p><input type = "submit" value = "Log in"></p>
if(!empty($_POST['logmail']) && !empty($_POST['logpass']))
{
$sql = ("SELECT customer_mail FROM customer_user WHERE customer_mail = '{$_POST['logmail']}'");
$sql2 = ("SELECT customer_pass FROM customer_user WHERE customer_pass = '{$_POST['logpass']}'");
$stmt = $dbh->prepare($sql);
$stmt2 = $dbh->prepare($sql2);
$stmt->execute();
$stmt2->execute();
var_dump($stmt->fetch());
var_dump($_POST['logmail']);
var_dump($stmt2->fetch());
var_dump($_POST['logpass']);
if($stmt->fetch()[0] == $_POST['logmail'])
{
if($stmt->fetch()[0] == $_POST['logpass'])
{
echo "Logged in";
}
else
{
echo "Wrong password";
}
}
else
{
?> <h2> Wrong email </h2> <?php
}
}
When I try to run this, the var_dumps gives me an arrays stmt->fetch() and stmt2->fetch. In position 0 of those arrays are the emails and passwords of the account I'm trying to login to. They are also the same as what I type into the fields in the form. The var_dumps for the $_POST confirms this.
But even thought they are the exact same, it doesn't trigger the If statement.
Does anyone know why this might be?
Why not fetchColumn() ? fetchColumn will by default return the first column of the next row instead of returning the entire row.
I didn't realize you were on the same table before. For a login form, you should be doing this a bit different in my opinion.
You should hash the password with a unique salt for each user. You should never store plain text passwords in your database.
You really only need one query:
$sql = ("SELECT customer_pass FROM customer_user WHERE customer_mail = ?");
Then you can compare the passwords (hopefully hashed)
Use one SQL query
$sql = ("SELECT customer_pass FROM customer_user WHERE customer_mail = ?");
$stm = $dbh->prepare($sql);
$stm->setFetchMode(PDO::FETCH_ASSOC);
$stm->execute($_POST['logmail']);
if ($stm && $stm->rowCount() == 1) {
$result = $stm->fetch();
if ($result['customer_pass'] === $_POST['logmail']) {
// Login
} else {
echo 'Wrong Password';
}
} else {
echo 'Email does not exist';
}
Next time get in the habit of Encrypting password while Registering and Login using SHA256 and Salt.
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 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.