<?php
session_start();
if(!isset($_SESSION['unique_id'])){
header("location: login.php");
}
?>
<?php include_once "header.php"; ?>
<body>
<div class="wrapper">
<section class="chat-area">
<header>
<?php
include_once "php/config.php";
$outgoing_id ="";
$incoming_id ="";
$message = "";
$user_id = mysqli_real_escape_string($conn, $_GET['user_id']);
$sql = mysqli_query($conn, "SELECT * FROM users WHERE unique_id = {$user_id}");
if(mysqli_num_rows($sql) > 0){
$row = mysqli_fetch_assoc($sql);
}
?>
<a href="users.php" class="back-icon">⬅</a>
<img src="php/images/<?php echo $row['img']; ?>" alt="">
<div class="details">
<span><?php echo $row['fname'] . " ". $row['lname']; ?></span>
<p><?php echo $row['status']?></p>
</div>
</header>
<div class="chat-box">
</div>
<form action="" class="typing-area" autocomplete="off" method="POST">
<input type="text" name="outgoing_id" value="<?php echo $_SESSION['unique_id']; ?>" hidden>
<input type="text" name="incoming_id" value="<?php echo $user_id; ?>" hidden>
<input type="text" name="message" class="input-field" name="" placeholder="Type here a message here...">
<button type="submit" name="submited" >➤</button>
</form>
</section>
</div>
<script src="javascript/chat.js"></script>
</body>
</html>
<?php
if (isset($_POST["submited"])) {
$outgoing_id = mysqli_real_escape_string($conn, $_POST['outgoing_id']);
$incoming_id = mysqli_real_escape_string($conn, $_POST['incoming_id']);
$message = mysqli_real_escape_string($conn, $_POST['message']);
if (!empty($message)) {
$sql = mysqli_query($conn, "INSERT INTO messages (incoming_msg_id, outgoing_msg_id, msg)
VALUES ('{$incoming_id}', '{$outgoing_id}', '{$message}')") or die();
}
}
?>
Now create new Folder as ("php") in htdocs/chatapp/
like as /htdocs/chatapp/php/
create new file as ("config.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/config.php
write source code as :
<?php
$conn = mysqli_connect("localhost", "root", "", "chat");
if(!$conn) {
echo "Database connection fail!" . mysqli_connect_error();
}
?>
Warnning Check localhost or real server conection connect or not:
create new file as ("data.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/data.php
write source code as :
<?php
while($row = mysqli_fetch_assoc($sql)) {
$sql2 = "SELECT * FROM messages WHERE (incoming_msg_id = {$row['unique_id']}
OR outgoing_msg_id = {$row['unique_id']}) AND (outgoing_msg_id = {$outgoing_id}
OR incoming_msg_id = {$outgoing_id}) ORDER BY msg_id DESC LIMIT 1 ";
$query2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_assoc($query2);
if(mysqli_num_rows($query2) > 0) {
$result = $row2['msg'];
}else {
$result = "No message available";
}
// trimming message if word are more than 28
(strlen($result) > 28) ? $msg = substr($result, 0, 28).'...' : $msg = $result;
// adding you : text before msg if login id send msg
($outgoing_id == $row2['outgoing_msg_id']) ? $you ="You: " : $you = "";
// check user is online or offline
($row['status'] == "Offline now") ? $offline = "offline" : $offline = "";
$output .= '
<a href="chat.php?user_id='.$row['unique_id'].'">
<div class="content">
<img src="php/images/' .$row['img']. '" alt="">
<div class="details">
<span>'. $row['fname'] . " ".$row['lname'].'</span>
<p>'.$you . $msg.'</p>
</div>
</div>
<div class="status-dot '.$offline.'"><i class="fas fa-circle"></i></div>
</a> ';
}
?>
create new file as ("get-chat.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/get-chat.php
write source code as :
<?php
session_start();
include_once "config.php";
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if (!empty($email) && !empty($password)) {
// let's check user entered email & password matched to databse any table row email and password
$sql = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}' AND password = '{$password}'");
if (mysqli_num_rows($sql)>0) {
// if users credentials matched
$row = mysqli_fetch_assoc($sql);
$status ="Active now";
// updating user status to active now if user login successfully
$sql2 = mysqli_query($conn, "UPDATE users SET status = '{$status}' WHERE unique_id = {$row['unique_id']}");
if ($sql2) {
$_SESSION['unique_id'] = $row['unique_id']; // using this session we user unique_id in other php file
echo "success";
}
} else {
echo "Email or Password is incorrect!";
}
} else {
echo "All input fields are required";
}
?>
now next create new file as ("logout.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/logout.php
write source code as :
<?php
session_start();
if(isset($_SESSION['unique_id'])){
include_once "config.php";
$outgoing_id = mysqli_real_escape_string($conn, $_POST['outgoing_id']);
$incoming_id = mysqli_real_escape_string($conn, $_POST['incoming_id']);
$output = "";
$sql = "SELECT * FROM messages
LEFT JOIN users ON users.unique_id = messages.outgoing_msg_id
WHERE (outgoing_msg_id = {$outgoing_id} AND incoming_msg_id = {$incoming_id})
OR (outgoing_msg_id = {$incoming_id} AND incoming_msg_id = {$outgoing_id}) ORDER BY msg_id ASC";
$query = mysqli_query($conn, $sql);
if(mysqli_num_rows($query)> 0 ) {
while($row = mysqli_fetch_assoc($query)){
if($row['outgoing_msg_id'] === $outgoing_id) {
// if this is equal to then he is a msg sender
$output .= '<div class="chat outgoing">
<div class="details">
<p>'. $row['msg'] .'</p>
</div>
<img src="php/images/'.$row['img'].'" alt="">
</div>';
}else {
// he is a reciever
$output .= '<div class="chat incoming">
<img src="php/images/'.$row['img'].'" alt="">
<div class="details">
<p>'. $row['msg'] .'</p>
</div>
</div>';
}
}
echo $output;
}
}else {
header("login.php");
}
?>
now next create new file as ("search.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/search.php
write source code as :
<?php
session_start();
include_once "config.php";
$outgoing_id = $_SESSION['unique_id'];
$searchTerm = mysqli_real_escape_string($conn, $_POST['searchTerm']);
$output = "";
$sql = mysqli_query($conn, "SELECT * FROM users WHERE NOT unique_id ={$outgoing_id} AND (fname LIKE '%{$searchTerm}%' OR lname LIKE '%{$searchTerm}%')");
if(mysqli_num_rows($sql)> 0) {
include_once "data.php";
} else {
$output .= "No user found related to your search";
}
echo $output;
?>
now next create new file as ("signup.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/signup.php
write source code as :
<?php
session_start();
include_once "config.php";
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
if(!empty($fname) && !empty($lname) && !empty($email) && !empty($password)){
// let's check user email is valid or not
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {//if email is valid
// let's check that email is already exists in database or not
$sql = mysqli_query($conn, "SELECT email FROM users WHERE email = '{$email}'");
if(mysqli_num_rows($sql) > 0) {
// if email already exist
echo "$email - This email already exist!";
} else{
// let's check user upload file or not
if(isset($_FILES['image'])) {
// if file is uploaded
$img_name = $_FILES['image']['name']; // getting user uploaded img name
$tmp_name = $_FILES['image']['tmp_name']; // this temporary name is used to save/move file in folder
// let's explode image and get the last extention like jpg png
$img_explode = explode('.', $img_name);
$img_ext = end($img_explode); // here we get the extension of an user uploaded img file
$extensions = ['jpg', 'jpeg','png']; // these are some valid image ext and we have store then in array
if(in_array($img_ext , $extensions) === true){
// if user uploaded img ext is matched with any array extension
$time = time(); // this will return us current ...
// we need this time because when you uploading user img to in our folder we rename user file with current time
//so all the img file will have a unique name
// let's move the user uploaded img to our particular folder
$new_img_name = $time.$img_name;
if(move_uploaded_file($tmp_name, "images/".$new_img_name)){
$status = "Active now"; // once user signed up then his status will be active now
$random_id = rand(time(), 10000000); // creating random id for user
// let's insert all user data inside table
$sql2 = mysqli_query($conn, "INSERT INTO users (unique_id, fname, lname, email, password, img, status)
VALUES('{$random_id}', '{$fname}','{$lname}','{$email}','{$password}', '{$new_img_name}', '{$status}')");
if($sql2) {
// if these data inserted
$sql3 = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}'");
if(mysqli_num_rows($sql3)> 0 ){
$row = mysqli_fetch_assoc($sql3);
$_SESSION['unique_id'] = $row['unique_id']; // using this session we used user unique_id in other php file
echo "success";
}
}else {
echo "Something went wrong!";
}
}
}else {
echo "Please select an Image file - jpeg, jpg, png!";
}
}else {
echo "Please select an Image file";
}
}
}else {
echo "$email - This is not a valid email!";
}
}else{
echo "All input are required";
}
?>
now next create new file as ("users.php") in htdocs/chatapp/
like as /htdocs/chatapp/php/users.php
write source code as :
<?php
session_start();
include_once "config.php";
$outgoing_id = $_SESSION['unique_id'];
$sql = mysqli_query($conn, "SELECT * FROM users WHERE NOT unique_id ={$outgoing_id}");
$output = "";
/*if(mysqli_num_rows($sql) == 1){
$output .= "No user are available to chat";
} else
*/if(mysqli_num_rows($sql) > 0) {
include_once "data.php";
}
echo $output;
?>
const form = document.querySelector(".typing-area"),
inputField = form.querySelector(".input-field"),
sendBtn = form.querySelector("button"),
chatBox = document.querySelector(".chat-box");
/*
form.onsubmit = (e)=>{
e.preventDefault(); // preventing form from submiting
}
*/
/*
sendBtn.onclick = ()=> {
// let's Start Ajax
let xhr = new XMLHttpRequest(); // creating XML object
xhr.onload = ()=>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
inputField.value = ""; //once message inserted into database then leave blank the input field
scrollToBottom();
}
}
}
// we have to send the form data through ajax to php
let formData = new FormData(form); // creating new formData object
xhr.send(formData); // sending the form data to php
} */
setInterval(()=> {
// let's Start Ajax
let xhr = new XMLHttpRequest(); // creating XML object
xhr.open("POST", "php/get-chat.php", true);
xhr.onload = ()=>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
chatBox.innerHTML = data;
if(!chatBox.classList.contains("active")){
// if active class not contains in chatbox then scroll to buttom
}
}
}
}
// we have to send the form data through ajax to php
let formData = new FormData(form); // creating new formData object
xhr.send(formData); // sending the form data to php
}, 500); // this function will run frequently after 500ms
function scrollToBottom(){
chatBox.scrollTop = chatBox.scrollHeight;
}
3 Comments
ReplyDeleteWarning
: Undefined array key "user_id" in
C:\xampp\htdocs\ChattingApp\chat.php
on line
14
Fatal error
: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 in C:\xampp\htdocs\ChattingApp\chat.php:15 Stack trace: #0 C:\xampp\htdocs\ChattingApp\chat.php(15): mysqli_query(Object(mysqli), 'SELECT * FROM u...') #1 {main} thrown in
C:\xampp\htdocs\ChattingApp\chat.php
on line
1
This is my error can you please respond me
you should not copy paste the database mysql user table - sorce code.
Deleteyou may be create all table manually and impelement the code
and check all case sensitive or spelling in the source code.
here display syntax error : so solution is please check all spelling or case sensitive source code.
thank you visiting our blog
ReplyDeleteWarning
: Undefined array key "user_id" in
C:\xampp\htdocs\ChattingApp\chat.php
on line
14
Fatal error
: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 in C:\xampp\htdocs\ChattingApp\chat.php:15 Stack trace: #0 C:\xampp\htdocs\ChattingApp\chat.php(15): mysqli_query(Object(mysqli), 'SELECT * FROM u...') #1 {main} thrown in
C:\xampp\htdocs\ChattingApp\chat.php
on line
1
This my error can you please respond me I dont what to do