I'm currently using Ajax & jQuery for my chat, some might say its stupidly complex but so long as I can get it working.
It works on the first friend result, how ever not on the other. What its doing is the chat-load.php (Ajax part) is creating a new query to select the friends details, which are then being put into a result query on the chat.php page.
Therefore it only displays one "Working" chat window for the 1st friend. I tried grabbing the previous friend_id from the chat.php query and using it in the chat-load.php query but it didn't seem to notice any data.
Here is an example of what I'm getting, 1st result full width meaning its working, other results not full width as not working with ajax.
This is my current setup:
chat.php
<?php $users = $db->query("SELECT DISTINCT users.id, users.firstname, users.lastname,
message.date, message.time, message.message, message.recipient, message.sender
FROM users
JOIN friends
ON users.id IN (friends.sender, friends.recipient)
JOIN message
ON (users.id = message.sender)
AND 75 IN (message.sender,message.recipient)
ORDER BY message.date DESC, message.time DESC"); ?>
<!-- Friends query -->
<?php $users = $db->query("SELECT IF(friends.sender = ".$_SESSION["user"]["id"].", friends.recipient, friends.sender) AS user_id
FROM friends
WHERE friends.sender = ".$_SESSION["user"]["id"]."
OR friends.recipient = ".$_SESSION["user"]["id"].""); ?>
<?php while($friend = $users->fetch_object()): ?>
<?php $friends = $db->query("SELECT firstname, lastname, id FROM users WHERE id = $friend->user_id "); ?>
<?php while($FriendName = $friends->fetch_object()): ?>
<div class="chat-box">
<div class="header">
<?= $FriendName->firstname ?> <?= $FriendName->lastname ?> <?= $FriendName->id ?>
</div>
<script>
$(window).load(function() {
$("#chat-box, #messages").animate({ scrollTop: $(document).height() }, 1000);
});
</script>
<script>
function loadlink(){
$('#messages').load('chat-load.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 100);
</script>
<div id="messages" class="messages">
</div>
<div class="input-box">
<form id="SendForm" class="SendMsg" role="form" method="post">
<input type="text" id="s_firstname" name="s_firstname" class="MsgInputHidden" value="<?= $_SESSION["user"]["firstname"] ?>" />
<input type="text" id="s_lastname" name="s_lastname" class="MsgInputHidden" value="<?= $_SESSION["user"]["lastname"] ?>" />
<input type="text" id="sender" name="sender" class="MsgInputHidden" value="<?= $_SESSION["user"]["id"] ?>" />
<input type="text" id="r_firstname" name="r_firstname" class="MsgInputHidden"value="<?= $FriendName->firstname ?>" />
<input type="text" id="r_lastname" name="r_lastname" class="MsgInputHidden"value="<?= $FriendName->lastname ?>" />
<input type="text" id="recipient" name="recipient" class="MsgInputHidden" value="<?= $FriendName->id ?>" />
<input type="text" id="ip" name="ip" class="MsgInputHidden" value="<?= $_SERVER["REMOTE_ADDR"] ?>" />
<input type="text" id="date" name="date" class="MsgInputHidden" value="<?= date('Y-m-d') ."\n" ?>" />
<?php
$now = time();
$utc_time = $now - intval(date('Z', $now));
?>
<input type="text" id="time" name="time" class="MsgInputHidden" value="<?= '' . date('H:i:s', $now) . '' ?>" />
<input id="message" type="text" name="message" style="width: 100%; overflow: scroll;">
<input id="submit" class="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
<script>
$("#submit").click(function(e) {
e.preventDefault();
var message = $("#message").val();
var s_firstname = $("#s_firstname").val();
var s_lastname = $("#s_lastname").val();
var sender = $("#sender").val();
var r_firstname = $("#r_firstname").val();
var r_lastname = $("#r_lastname").val();
var recipient = $("#recipient").val();
var ip = $("#ip").val();
var date = $("#date").val();
var time = $("#time").val();
var dataString = '&message=' + message + '&s_firstname=' + s_firstname + '&s_lastname=' + s_lastname + '&sender=' + sender + '&r_firstname=' + r_firstname + '&r_lastname=' + r_lastname + '&recipient=' + recipient + '&ip=' + ip + '&date=' + date + '&time=' + time;
$.ajax({
type:'POST',
data:dataString,
url:'sendmessagefriend.php',
});
});
</script>
<script>
$("#submit").click(function(e) {
$("#SendForm").get(0).reset();
});
</script>
<script>
$("#submit").click(function(e) {
$("#chat-box, #messages").animate({ scrollTop: $(document).height() }, 1000);
});
</script>
<?php endwhile; ?>
<?php endwhile; ?>
chat-load.php
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
if(!isset($_SESSION["user"]) or !is_array($_SESSION["user"]) or empty($_SESSION["user"])
)
// redirect to index page if not superuser
header('Location: index.php');
?>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','****','****','****');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT message, sender, recipient, date, time, IF(recipient = ".$_SESSION["user"]["id"].", 'received', 'sent') AS direction FROM message WHERE recipient IN (".$_SESSION["user"]["id"].", ".$friend->user_id.") AND sender IN (".$_SESSION["user"]["id"].", ".$friend->user_id.")";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<ul>";
echo "<li>";
echo "<span class='". $row['direction'] ."'>". $row['message'] ."</span>";
echo "<div class='clear'></div>";
echo "</li>";
echo "</ul>";
}
mysqli_close($con); ?>
</body>
</html>
Try using $.ajax() instead of $.load(). Set cache: false.
Example:
function loadlink(){
$.ajax({
url:'chat-load.php',
cache: false,
success: function(result){
$('#messages').html(result);
}
});
}
Related
I don't know why my code does not work onclick, but there is no pop up. The AJAX function var phone and id got data, but the AJAX did not. Is there anything wrong with the script? Does the AJAX need a jQuery library?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript">
function clickButton() {
var phone = document.getElementById('phone').value;
var id = document.getElementById('id').value;
$.ajax({
type: "post",
url: "userDetaiAjax.php",
data: {
'phone': phone,
'id': id
},
cache: false,
success: function(html) {
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
<div class="col">
<div class="form-group">
<h6>
<label>Name :</label>
<?php echo $name ?>
</h6>
<h6>
<label>Email :</label>
<?php echo $email ?>
</h6>
<input type="" name="phone" id="phone">
<input type="" name="id" id="id" value="<?php echo $_SESSION[" staff_id "];?>" hidden>
<h6>
<label>Phone :</label>
<?php echo $phone ?>
</h6>
<input type="submit" name="aa" value="submit2" onclick="return clickButton();">
</form>
<p id="msg"></p>
</div>
</div>
</div>
</div>
for the url
<?php
$phone = $_POST['phone'];
$id = $_POST['id'];
echo 'success';
echo $phone;
echo $id;
$a='"USR_ID"';
$b='"phone"';
include 'conn.php';
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$query = "update usr_web SET phone=:c1 WHERE usr_id=:c2";
$stid = oci_parse($conn, $query);
oci_bind_by_name($stid, ":c1", $phone);
oci_bind_by_name($stid, ":c2", $id);
$result = oci_execute($stid);
oci_free_statement($stid);
oci_commit($conn);
oci_close($conn);
echo $result;
?>
When you open the console of your browser you should see an error message like "ReferenceError: $ is not defined". So it seems that $ is not part of core.js which you have loaded. Just load the full version (https://code.jquery.com/jquery-3.3.1.min.js) and it should work.
U have error in your console:
$ is not defined
Which mean u did not include jquery, so u should add this code after ajax include:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
U can chack your console errors with F12 key in browser and tab Console.
I have my comment form in fullpost page and I am proccessing a form using ajax, but I don't know how to insert post_id in my comments table to specify the post comment. Kindly help
as I am trying to get the get_id in sql.php but I'm gettng an error which shows undefined post_id in line 13 sql.php
Please find my code below:
fullpost.php
?php
ob_start();
require_once('includes/header.php'); ?>
<?php
$db = new Database();
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT * FROM posts WHERE post_id ='$id'";
$post = $db->select($query);
}
$c_query = "SELECT * FROM comments WHERE post_id='$id' ORDER BY comment_id DESC";
$c_run = $db->select($c_query);
?>
<div class ="col-8">
<div class="content-area">
<?php if($post):?>
<?php while($row = $post->fetch_array()):?>
<h2 class="title-full-post"><?php echo $row['title'];?></h2>
<p class="content-area-auth"><?php echo formatDate($row['created_date']);?> By
<a class="content-area-author" href=""><?php echo $row['author']; ?></a></p>
<img class="post-img" src="assets/images/<?php echo $row['image']; ?>">
<p class="content-area-body"><?php echo $row['body'];?><br /><br /><br />
</p>
<?php endwhile; ?>
<?php endif; ?>
<div class="comment">
<h2>Recent Comments</h2>
<?php
if($c_run):
while($r = $c_run->fetch_assoc()):
?>
<p><?php echo $r['name']; echo $r['date']; ?></p>
<p><?php echo $r['comment']; ?></p>
<!--<input type='button' name='reply' id='reply' value='Reply' onclick='replyComment("<?php echo $message_id?>")' />-->
<hr>
<?php
endwhile;
endif;
?>
</div>
<div class="comments-area" id="editbutton">
<h2>Comment Below</h2>
<form action="fullpost" id ="commentForm" method="post" class="form-commment">
<input type="hidden" name="commentId" value="<?php echo $id ?>">
<label for="">Name</label><span style="color: red;">*</span>
<input type="text" name="name" id="commentName" class="form-control-comment" placeholder="Type your Name..">
<label for="">Email</label>
<input type="Email" name="email" id="commentEmail" class="form-control-comment" placeholder="Type your Email..">
<label for="">Website</label>
<input type="text" name="website" id="commentWebsite" class="form-control-comment" placeholder="Type your Website..">
<label for="">Comment</label>
<textarea name="comment" id="commentMessage" class="form-control-comment form-text-area">Comment ...</textarea>
<input type="submit" id="submitComment" name="submitComment" class="btn-comment" value="Post Comment">
<span id="errorMessage"></span>
<span id="successMessage"></span>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#commentForm").submit(function(event){
event.preventDefault();
var commentName = $("#commentName").val();
var commentEmail = $("#commentEmail").val();
var commentWebsite = $("#commentWebsite").val();
var commentMessage = $("#commentMessage").val();
if(commentName == '' || commentEmail == '' || commentMessage == '' ){
$("#errorMessage").html("Fill all the required fields");
} else{
$("#errorMessage").html('');
$.ajax({
url: "sql.php",
type: "POST",
async: false,
data:{
"done": 1,
"username": commentName,
"useremail": commentEmail,
"userwebsite": commentWebsite,
"usercomment": commentMessage,
"commentId": commentId
},
success: function(data){
//$("#name").val('');
//$("#message").val('');
$("form").trigger("reset");
$("#successMessage").fadeIn().html(data);
}
});
}
});
});
</script>
</div><!--End of Content Area-->
</div><!--end of col-8-->
<?php require_once('includes/footer.php'); ?>
<!--- this is sql.php-->
<?php
require_once('config/config.php');
require_once('libraries/database.php');
require_once('helpers/format_helpers.php');
//require_once('includes/header.php');
//$conn= new mysqli('localhost','root','','myblog');
$db = new Database();
//$id = $_GET['id'];
/*Insert comments*/
if(isset($_POST['done'])){
$name = mysqli_real_escape_string($db->link, $_POST['username']);
$email = mysqli_real_escape_string($db->link, $_POST['useremail']);
$website = mysqli_real_escape_string($db->link, $_POST['userwebsite']);
$comment = mysqli_real_escape_string($db->link, $_POST['usercomment']);
$postId = mysqli_real_escape_string($db->link, $_POST
['commentId']);
if(!empty($name && $email && $comment)){
// $conn= new mysqli('localhost','root','','myblog');
$i_query ="INSERT INTO comments(name, email, website, comment, post_id)VALUES('$name','$email','$website','$comment','$postId')";
$insert_query =$db->insert($i_query);
if($insert_query){
echo "Comment has been submitted and waiting for approval..";
} else{
$error_message ="Please try again..comment not submitted";
}
} else{
$error_message ="All(*)Fields Are required";
}
}
Any assistance would be greatly appreciated
You can use mysql_insert_id() to return the last ID generated my MySQL.
If you show your Database class I can give you an example.
I have a comment system that is working fine. But now I wanna make it work into a loop, so it needs is add an id to identify as unique every "comment box", "submit buttom", so on. Due to there are many classes involved I got lost adding the index to the js function ... and actually everything.
This is my code:
<?php
$sql = mysql_query("SELECT * FROM tblopiniones_persopoli WHERE id_post = '$id_post' AND intActivo = '1' LIMIT 0,10") or die(mysql_error());
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['intName'];
$email = $affcom['email'];
$comment = $affcom['strComment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ObtenerNombreFull_Usuario($name); ?></h5><span data-utime="1371248446" class="com-dt"></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt" id="<?php echo $m; ?>">
<span id="">Escribe un comentario ...</span>
</div>
<div class="new-com-cnt">
<a name="coment_box" id="coment_box">
<input type="hidden" id="name-com" name="name-com" value="<?php echo $_SESSION['MM_IdUser']; ?>" />
<input type="hidden" id="mail-com" name="mail-com" value="<?php echo 'xxxxxxx#gmail.com'; ?>" />
<input type="hidden" id="pic-com" name="pic-com" value="<?php echo ObtenerNombreFoto_Usuario($_SESSION['MM_IdUser']); ?>" />
<textarea class="the-new-com" placeholder="Ingresa tu comentario"></textarea>
<div class="bt-add-com">Publicar comentario</div>
<div class="bt-cancel-com">Cancelar</div>
</a>
</div>
My Js code:
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#coment_box').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
var thePic = $('#pic-com');
if( !theCom.val()){
alert('¡Por favor escribe un comentario!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val()+'&pic='+thePic.val(),
success: function(html){
theCom.val('');
/*theMail.val('');
theName.val('');*/
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
I'll highly appreciate any help with this lack of knowledge & expertise.
Many thanks in advance.
SO i have this piece of AJAX that work as it should be but i want to add some validation to it.I dont want it to send empty information.The AJAX is done for a comment system.It takes the value from the form and then with php it inserts it to the databse. The Problem i am haveing is that it just insert empty comment to the database
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<script type="text/javascript">
function validateForm()
{
var comment = document.getElementsByName('comment').value;
if (comment == "" )
{
alert("Please fill in all the fields");
return false;
}
else
{
return true;
}
}
</script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" onsubmit="return validateForm();">
<label>New Comment</label>
<textarea name="comment" class="comment"> </textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
My AJAX code.I have tried to do some validation but it doesnt work properly and i dont know what is wrong with it.I am quite new to AJAX so not rlealy able to debug it myself.
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('.comment');
if (!comment.val()){
alert('You need to write a comment!');
}
else{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
});
});
My php code to insert into the database.
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
include('connection.php');
$connection = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['username'];
$postId = $_POST['postid'];
$comment = $_POST['comment'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tblcomments`
(`Content`,`UserID`,`PostID`,`Timestamp`)
VALUES (
'$comment','$userId','$postId',
CURRENT_TIMESTAMP)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>
You never call the function validateForm()
And this part
if (!comment.val()){
alert('You need to write a comment!');
}
will always pass if there is a input field with the class comment, even if it's empty. You could do something like:
//send ajax request
if(validateForm()===false){
alert('You need to write a comment!');
return false;
}
else{
....
You could try to change the comment.val() to comment.text() since you are using a textarea and see if that solves your problem. The change is to be modified in your js code
I have this sign-in page...
<!doctype html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<form action="signin_process.php" method="post">
Name: <input type="text" name="name">
<br />
SID: <input type="text" name="sid">
<br />
Nick Name: <input type="text" name="nn">
<br />
Email: <input type="text" name="email">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
The signin_process.php file...
<!doctype html>
<html>
<head>
<title>Signin_process</title>
</head>
<body>
<?php
include ("connection.php");
$name = $_POST['name'];
$sid = $_POST['sid'];
$nn = $_POST['nn'];
$em = $_POST['email'];
$pw = $_POST['pw'];
$result = mysqli_query($con, "SELECT * FROM student_table WHERE SID='$sid'") or die('Query failed');
if(mysqli_num_rows($result)){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Invalied SID')
window.location.href='welcome.php';
</SCRIPT>");
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE nickname='$nn'") or die('Query failed');
if(mysqli_num_rows($result)){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Nickname Takken!')
window.location.href='welcome.php';
</SCRIPT>");
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE email='$em'") or die('Query failed');
if(mysqli_num_rows($result)){
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Email already in use!')
window.location.href='welcome.php';
</SCRIPT>");
}
?>
</body>
</html>
Now if SID, Nick name or email is not valid, i want to redirect to the sign-in page and the field values will be there which were given earlier. So that in don't have to input all the values all over again. Like we see in many sites, we just had to change the input that was not excepted and submit again.
Thanks!
You can use like this:
if ($_POST['name'] == '') {
echo "<script type='text/javascript'>window.history.back();</script>";
}
By this way field values will be there which were given earlier.
<?php
session_start();
if(isset($_POST['nam']) && (isset($_POST['sid']) && (isset($_POST['nn'])){
if(($_POST['name']=== 'user')&& ($_POST['sid']==='sid')&&($_POST['nn']==='sid')){
echo "correct";
$_SESSION['us'] = "YES";
$_SESSION['sid'] = "YES";
$_SESSION['nn'] = "YES";
header("location: userpage.php"); //directs to user area
}else {
echo "Wronge Password/Name/Nickname";
$_SESSION['us'] = $_POST['name'];
$_SESSION['sid'] = $_POST['sid'];
$_SESSION['nn'] = $_POST['nn'];
header("location: userpage.php"); //userpage redirects to this page
}}
?>
<!doctype html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<form action="" method="post">
Name: <input type="text" name="name" <?php echo isset($_SESSION['us']) ? $_SESSION['us'] : ""; ?> >
<br />
SID: <input type="text" name="sid" <?php echo isset($_SESSION['sid']) ? $_SESSION['sid'] : ""; ?> >
<br />
Nick Name: <input type="text" name="nn" <?php echo isset($_SESSION['sid']) ? $_SESSION['sid'] : ""; ?> >
</form>
</body>
</html>
A basic example:
Your login form:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<ul>
<?php
$errors = isset($_SESSION['errors']) && is_array($_SESSION['errors']) ? $_SESSION['errors'] : [];
foreach ($errors as $error):
?>
<li><?php print $error; ?></li>
<?php endforeach; ?>
</ul>
<form action="signin_process.php" method="post">
<label for="name">Name: </label>
<input type="text" id="name" name="name" value="<?php print !isset($_SESSION['name']) ?: $_SESSION['name']; ?>" />
<label for="sid">SID: </label>
<input type="text" id="sid" name="sid" value="<?php print !isset($_SESSION['sid']) ?: $_SESSION['sid']; ?>" />
<label for="nn">Nick Name: </label>
<input type="text" id="nn" name="nn" value="<?php print !isset($_SESSION['nn']) ?: $_SESSION['nn']; ?>" />
<label for="email">Email: </label>
<input type="text" id="email" name="email" value="<?php print !isset($_SESSION['email']) ?: $_SESSION['email']; ?>" />
<label for="pw">Password: </label>
<input type="text" id="pw" name="pw" value="<?php print !isset($_SESSION['pw']) ?: $_SESSION['pw']; ?>" />
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
Your PHP form submission:
<?php
session_start();
include ("connection.php");
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_SESSION['name'] = mysqli_real_escape_string($con, $_POST['name']);
$sid = $_SESSION['sid'] = mysqli_real_escape_string($con, $_POST['sid']);
$nn = $_SESSION['nn'] = mysqli_real_escape_string($con, $_POST['nn']);
$em = $_SESSION['email'] = mysqli_real_escape_string($con, $_POST['email']);
$pw = $_SESSION['pw'] = mysqli_real_escape_string($con, $_POST['pw']);
$_SESSION['errors'] = [];
$result = mysqli_query($con, "SELECT * FROM student_table WHERE SID='$sid'") or die('Query failed');
if (mysqli_num_rows($result) > 0) {
$_SESSION['errors'][] = 'Invalid SID.';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit();
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE nickname='$nn'") or die('Query failed');
if (mysqli_num_rows($result) > 0) {
$_SESSION['errors'][] = 'Nickname already in use.';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit();
}
$result = mysqli_query($con, "SELECT * FROM student_table WHERE email='$em'") or die('Query failed');
if (mysqli_num_rows($result) > 0) {
$_SESSION['errors'][] = 'E-mail already in use.';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit();
}
}
header('Location: index.php');
exit();
?>
That should work.
P.S. You should look into prepared statements and input filtering. Safety should always come first.