I have a xamp based webserver and I installed attendance system , I have 10 users registered to enter their attendance by login individually... issue is in login page accept any password and not giving error that password is wrong. Like you enter user id john#abcd.com & password gfjhgh its accept and entered to index page , the original password is 123456 but its accept every thing you type. Please tell me how to solve. It should says that you entered wrong password and can not login.
Code is below:
// Account Log In
if (isset($_POST['submit']) && $_POST['submit'] == 'signIn') {
if($_POST['emailAddy'] == '') {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else if($_POST['password'] == '') {
$msgBox = alertBox($accPassReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['emailAddy']);
$check = "SELECT userId, userFirst, userLast, isActive FROM users WHERE userEmail = '".$usrEmail."'";
$res = mysqli_query($mysqli, $check) or die('-1' . mysqli_error());
$row = mysqli_fetch_assoc($res);
$count = mysqli_num_rows($res);
if ($count > 0) {
// If the account is Active - Allow the login
if ($row['isActive'] == '1') {
$userEmail = htmlspecialchars($_POST['emailAddy']);
$password = encodeIt($_POST['password']);
if($stmt = $mysqli -> prepare("
SELECT
userId,
userEmail,
userFirst,
userLast,
location,
superUser,
isAdmin
FROM
users
WHERE
userEmail = ?
AND password = ?
")) {
$stmt -> bind_param("ss",
$userEmail,
$password
);
$stmt -> execute();
$stmt -> bind_result(
$userId,
$userEmail,
$userFirst,
$userLast,
$location,
$superUser,
$isAdmin
);
$stmt -> fetch();
$stmt -> close();
if (!empty($userId)) {
if(!isset($_SESSION))session_start();
$_SESSION['tz']['userId'] = $userId;
$_SESSION['tz']['userEmail'] = $userEmail;
$_SESSION['tz']['userFirst'] = $userFirst;
$_SESSION['tz']['userLast'] = $userLast;
$_SESSION['tz']['location'] = $location;
$_SESSION['tz']['superUser'] = $superUser;
$_SESSION['tz']['isAdmin'] = $isAdmin;
// Add Recent Activity
$activityType = '1';
$tz_uid = $userId;
$activityTitle = $userFirst.' '.$userLast.' '.$accSignInAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// Update the Last Login Date for User
$sqlStmt = $mysqli->prepare("UPDATE users SET lastVisited = NOW() WHERE userId = ?");
$sqlStmt->bind_param('s', $userId);
$sqlStmt->execute();
$sqlStmt->close();
header('Location: index.php');
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = '0';
$activityTitle = $accSignInErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
$msgBox = alertBox($accSignInErrMsg, "<i class='fa fa-warning'></i>", "warning");
}
}
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = $row['userId'];
$activityTitle = $row['userFirst'].' '.$row['userLast'].' '.$signInUsrErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// If the account is not active, show a message
$msgBox = alertBox($inactAccMsg, "<i class='fa fa-warning'></i>", "warning");
}
} else {
// Add Recent Activity
$activityType = '0';
$tz_uid = '0';
$activityTitle = $noAccSignInErrAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// No account found
$msgBox = alertBox($noAccSignInErrMsg, "<i class='fa fa-times-circle'></i>", "danger");
}
}
}
// Reset Account Password
if (isset($_POST['submit']) && $_POST['submit'] == 'resetPass') {
// Validation
if ($_POST['accountEmail'] == "") {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['accountEmail']);
$query = "SELECT userEmail FROM users WHERE userEmail = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s",$usrEmail);
$stmt->execute();
$stmt->bind_result($emailUser);
$stmt->store_result();
$numrows = $stmt->num_rows();
if ($numrows == 1) {
// Generate a RANDOM Hash for a password
$randomPassword = uniqid(rand());
// Take the first 8 digits and use them as the password we intend to email the Employee
$emailPassword = substr($randomPassword, 0, 8);
// Encrypt $emailPassword for the database
$newpassword = encodeIt($emailPassword);
//update password in db
$updatesql = "UPDATE users SET password = ? WHERE userEmail = ?";
$update = $mysqli->prepare($updatesql);
$update->bind_param("ss",
$newpassword,
$usrEmail
);
$update->execute();
$qry = "SELECT userId, userFirst, userLast, isAdmin FROM users WHERE userEmail = '".$usrEmail."'";
$results = mysqli_query($mysqli, $qry) or die('-2' . mysqli_error());
$row = mysqli_fetch_assoc($results);
$theUser = $row['userId'];
$isAdmin = $row['isAdmin'];
$userName = $row['userFirst'].' '.$row['userLast'];
if ($isAdmin == '1') {
// Add Recent Activity
$activityType = '3';
$activityTitle = $userName.' '.$admPassResetAct;
updateActivity($theUser,$activityType,$activityTitle);
} else {
// Add Recent Activity
$activityType = '3';
$activityTitle = $userName.' '.$usrPassResetAct;
updateActivity($theUser,$activityType,$activityTitle);
}
$subject = $siteName.' '.$resetPassEmailSub;
$message = '<html><body>';
$message .= '<h3>'.$subject.'</h3>';
$message .= '<p>'.$resetPassEmail1.'</p>';
$message .= '<hr>';
$message .= '<p>'.$emailPassword.'</p>';
$message .= '<hr>';
$message .= '<p>'.$resetPassEmail2.'</p>';
$message .= '<p>'.$resetPassEmail3.' '.$installUrl.'sign-in.php</p>';
$message .= '<p>'.$emailTankYouTxt.'<br>'.$siteName.'</p>';
$message .= '</body></html>';
$headers = "From: ".$siteName." <".$siteEmail.">\r\n";
$headers .= "Reply-To: ".$siteEmail."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($usrEmail, $subject, $message, $headers);
$msgBox = alertBox($resetPassMsg1, "<i class='fa fa-check-square'></i>", "success");
$stmt->close();
} else {
// Add Recent Activity
$activityType = '1';
$tz_uid = '0';
$activityTitle = $resetPassMsgAct;
updateActivity($tz_uid,$activityType,$activityTitle);
// No account found
$msgBox = alertBox($resetPassMsg2, "<i class='fa fa-times-circle'></i>", "danger");
}
}
}
if (isset($_POST['submit']) && $_POST['submit'] == 'signIn') {
if($_POST['emailAddy'] == '') {
$msgBox = alertBox($accEmailReq, "<i class='fa fa-times-circle'></i>", "danger");
} else if($_POST['password'] == '') {
$msgBox = alertBox($accPassReq, "<i class='fa fa-times-circle'></i>", "danger");
} else {
$usrEmail = htmlspecialchars($_POST['emailAddy']);
$password = encodeIt($_POST['password']);
$check = "SELECT userId, userFirst, userLast, isActive FROM users WHERE userEmail = '".$usrEmail."'";
$res = mysqli_query($mysqli, $check) or die('-1' . mysqli_error());
$row = mysqli_fetch_assoc($res);
$count = mysqli_num_rows($res);
if ($count > 0) {
I'm only assuming that the first time you tried to login is that the session was save and you did not destroy the session.
if ((isset($_SESSION['tz']['userId'])) && ($_SESSION['tz']['userId'] != '')) {
header('Location: index.php');
}
thus making that condition always true.
If you want to prevent/avoid the user in logging in without the valid credentials.
Matching the records in the DB
$check = "SELECT userEmail, password FROM users WHERE userEmail = '".$usrEmail."' AND password = '".$password."'";
$res = mysqli_query($mysqli, $check) or die('-1' . mysqli_error());
$row = mysqli_fetch_assoc($res);
$count = mysqli_num_rows($res);
if ($count > 0) {
//match found
}
else {
//no match found or username/password doesn't match
}
Related
I´m using the jquery based table plugin "datatables" and I´m trying to implement an ajax based "range search" between two numbers ("start-date" and "end_date"). These entered values should be used for a query in the MySQL column "order_id".
On the server-sided script (fetch.php) I catch the both values like that.
if(isset($_POST['start_date'], $_POST['end_date'])) {
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
The problem is I can´t see any errors in the console, but after using the number range search no results are displayed.
The "category select menus" (category and category2) are working as expected.
I´ve setted up a test site, maybe you can help me to find the error: Testsite
This is my script:
$(document).ready(function () {
var category = "";
var category2 = "";
var start_date = "";
var end_date = "";
load_data();
function load_data(is_category, is_category2, start_date, end_date) {
console.log(is_category, is_category2, start_date, end_date);
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_category: is_category,
is_category2: is_category2,
start_date: start_date,
end_date: end_date
},
}
});
}
// Number Range Search
$('#search').click(function () {
console.log($(this).attr('id'), start_date, end_date)
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if (start_date != '' && end_date != '') {
$('#product_data').DataTable().destroy();
load_data('','',start_date, end_date);
}
else {
alert("Both Date is Required");
}
});
// Select Menu id="category"
$(document).on('change', '#category, #category2', function () {
//console.log($(this).attr('id'), category, category2)
if ($(this).attr('id') === "category") {
category = $(this).val();
} else if ($(this).attr('id') === "category2") {
category2 = $(this).val();
}
//
$('#product_data').DataTable().destroy();
if (category != '') {
load_data(category, category2);
}
else {
load_data();
}
});
// Select Menu id="category2"
$(document).on('change', '#category2', function () {
var category2 = $(this).val();
$('#product_data').DataTable().destroy();
if (category2 != '') {
load_data(category, category2);
}
else {
load_data();
}
});
});
fetch.php
//fetch.php
$connect = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxxx");
$columns = array('order_id', 'order_customer_name', 'order_item', 'order_value', 'order_date');
$query = "SELECT * FROM tbl_order WHERE ";
if(isset($_POST['start_date'], $_POST['end_date']))
{
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["is_category"]))
{
$query .= "order_item = '".$_POST["is_category"]."' OR ";
}
if(isset($_POST["is_category2"]))
{
$query .= "order_customer_name = '".$_POST["is_category2"]."' AND ";
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(order_id LIKE "%'.$_POST["search"]["value"].'%"
OR order_customer_name LIKE "%'.$_POST["search"]["value"].'%"
OR order_item LIKE "%'.$_POST["search"]["value"].'%"
OR order_value LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY order_id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = $row["order_id"];
$sub_array[] = $row["order_customer_name"];
$sub_array[] = $row["order_item"];
$sub_array[] = $row["order_value"];
$sub_array[] = $row["order_date"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM tbl_order";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
Thats because the is_category and is_category2 are returning 0. You have probably an if statement on your php like if $_POST[is_category] but you also need to do the same in case there is no category selected. Please share the full php to help you out
on your click function replace load_data(start_date, end_date); with load_data('','',start_date, end_date);
i have a php website linked with Sql Server database, im trying to get data from the database and show it on the page in a table but when it create the table it show me the message "No results found" , what is the code to get the info from the database and show it in the website?
ps:im using jquery.bootgrid
<?php
include 'dbh.inc.php';
$query='';
$data=array();
$records_per_page= 10;
$start_from= 0;
$current_page_number= 0;
if(isset($_POST["rowCount"]))
{
$records_per_page= $_POST["rowCount"];
}
else
{
$records_per_page= 10;
}
if(isset($_POST["current"]))
{
$records_per_page= $_POST["current"];
}
else
{
$records_per_page= 1;
}
$star_from= ($current_page_number - 1)* $records_per_page;
$query .="SELECT * FROM Employee";
if(!empty($_POST["searchPhrase"]))
{
$query .= 'where (Id like "%'.$_POST["searchPhrase"].'%")';
$query .= 'or First_Name like "%'.$_POST["searchPhrase"].'%" ';
$query .= 'or Last_Name like "%'.$_POST["searchPhrase"].'%" ';
$query .= 'or username like "%'.$_POST["searchPhrase"].'%" ';
}
$order_by = '';
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key =>$value )
{
$order_by = '$key $value,';
}
}
else
{
$query .= 'order by Id Desc';
}
if($order_by != '')
{
$query .= ' order by ' . substr($order_by,0,-2);
}
if($records_per_page != -1)
{
$query .= "LIMIT" .$star_from. "," .$records_per_page;
}
$result = sqlsrv_query($conn, $query);
while($row=sqlsrv_fetch_array($result))
{
$data[]=$row;
}
$query1 .="SELECT * FROM Employee";
$result1 = sqlsrv_query($conn, $query1);
$total_records=sqlsrv_has_rows($result1);
$output=array('current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($total_records),
'rows' => $data );
echo json_encode($output);
?>
I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't.
When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine.
This is the request script:
function getcolours() {
var hr = new XMLHttpRequest();
hr.open("GET", "camp_map_script.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
for (var obj in data) {
number = data[obj].number;
colour = data[obj].colour;
neighbour1 = data[obj].n1;
alert (neighbour1);
window["colour" + number] = colour;
var x = document.getElementsByClassName(number + ' ' + colour);
x[0].style.display = "block";
}
}
}
hr.send(null);
}
This is the php part:
<?php
include_once("../php_includes/check_login_status.php");
?><?php
$number = "";
$sql = "SELECT camp_id FROM users WHERE username='$log_username'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$campid = $row[0];
$sql = "SELECT players FROM campaigns WHERE id='$campid'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$players = $row[0];
$number = ($players*2)-1;
$sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number";
$query = $connect->query($sql);
$jsonData = '{';
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},';
}
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
$connect->close();
?>
Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit.
It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/
I'm creating a login script in PHP and JS. I would like to have a different error messages in my form but unfortunately not everything works fine. For example checking whether there is such a user is working well but if I type a properly email and incorrect password I will be redirected to profile.php?u=%3Cbr%20/%3E%3Cb%3ENotice%3C/(...). Where I made a mistake?
login.php
if(isset($_POST["e_l"])){
include_once("db/db_fns.php");
$e = mysqli_real_escape_string($db_conx, $_POST['e_l']);
$p = $_POST['p_l'];
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
if($e == "" || $p == ""){
$message = preg_replace('/[\/_| -]+/', '', 'loginfailed');
echo $message;
exit();
} else {
$sql = "SELECT id, username, password, activated FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$activated = $row['activated'];
$number = mysqli_num_rows($query);
if ($number <=0){
$message = preg_replace('/[\/_| -]+/', '', 'nouser');
echo $message;
exit();
} else {
if ($activated = '0') {
$message = preg_replace('/[\/_| -]+/', '', 'noactiv');
echo $message;
exit ();
} else {
$db_id = $row[0];
$db_username = $row[1];
$db_pass_str = $row[2];
if (password_verify ($p, $db_pass_str)) {
$_SESSION['userid'] = $db_id;
$_SESSION['username'] = $db_username;
$_SESSION['password'] = $db_pass_str;
setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE);
$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo $db_username;
exit();
} else{
$message = preg_replace('/[\/_| -]+/', '', 'loginfailed');
echo $message;
exit();
}
}
}
}
exit();
}
login.js
function login(){
var e_l = _("email_l").value;
var p_l = _("password_l").value;
if(e_l == "" || p_l == ""){
_("status_l").innerHTML = '<div class="message_b"><img src="images/error.gif"/> Fill out all of the form data</div>';
} else {
_("loginbtn").style.display = "none";
_("status_l").innerHTML = '<img src="images/wait.gif"/>';
var ajax = ajaxObj("POST", "login.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if (ajax.responseText.trim() == "nouser"){
_("status_l").innerHTML = '<div class="message_b"><img src="images/error.gif"/> Wrong username</div>';
_("loginbtn").style.display = "block";
} else if (ajax.responseText.trim() == "noactiv"){
_("status_l").innerHTML = '<div class="message_b"><img src="images/error.gif"/> Your account is no active</div>';
_("loginbtn").style.display = "block";
} else if (ajax.responseText.trim() == "loginfailed"){
_("status_l").innerHTML = '<div class="message_b"><img src="images/error.gif"/> Login unsuccessful, please try again</div>';
_("loginbtn").style.display = "block";
} else {
window.location = "profile.php?u="+ajax.responseText;
}
}
}
ajax.send("e_l="+e_l+"&p_l="+p_l);
}
}
Judging by what you're saying and your code, it seems that password_verify isn't working for you. Are you sure the passowrd in the database has been hashed with PHP's password_hash?
Hi I have used a code snippet from a tutorial for a chat application all of its scripts are working fine but after I tweak it to make the code work based on my requirements almost all of the scripts are working except for retrieving the conversation
The error I'm having is it doesn't retrieve the conversation from my database
here is the modified script
//Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$json .= '"message":[ {';
$json .= '"id": "0",
"user": "Admin",
"text": "You are not currently in a chat session. <a href="">Enter a chat session here</a>",
"time": "' . date('h:i') . '"
}]';
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$json .= '"message":[ ';
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json .= '{';
$json .= '"id": "' . $message_array['msgid'] . '",
"user": "' . htmlspecialchars($message_array['username']) . '",
"text": "' . htmlspecialchars($message_array['message_content']) . '",
"time": "' . $message_array['message_time'] . '"
},';
}
$json .= ']';
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$json .= '"message":[]';
}
}
//Close our response
$json .= '}}';
echo $json;
Here is the code for calling this script
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
getChatText();
}
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
//Get a reference to our chat container div for easy access
var chat_div = document.getElementById('clog');
var response = eval("(" + receiveReq.responseText + ")");
for(i=0;i < response.messages.message.length; i++) {
chat_div.innerHTML += response.messages.message[i].user;
chat_div.innerHTML += ' <font class="chat_time">' + response.messages.message[i].time + '</font><br />';
chat_div.innerHTML += response.messages.message[i].text + '<br />';
chat_div.scrollTop = chat_div.scrollHeight;
lastMessage = response.messages.message[i].id;
}
mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
}
}
Am I missing something here or doing something wrong?
You should rewrite using json_encode:
$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$message_object = (object) array(
"id"=>"0",
"user"=>"Admin",
"text"=>"You are not currently in a chat session. <a href=\"\">Enter a chat session here</a>",
"time"=>date('h:i')
);
$messages[] = (object) array("message"=>$message_object);
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$message_object = (object) array(
"id"=>$message_array['msgid'],
"user"=>htmlspecialchars($message_array['username']),
"text"=>htmlspecialchars($message_array['message_content']),
"time"=>$message_array['message_time'
);
$messages[] = (object) array("message"=>$message_object);
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$messages[] = (object) array("message"=>array());
}
}
//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;