Login in PHP with JS error messages - javascript

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?

Related

Ajax based range search in jquery plugin "Datatables"

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);

bad request error in angularjs

var successCallback=function(response) {
if(response.success) {
$log.log(response.data);
alert('fetched courses and percentages successfully');
} else {
}
};
var errorCallback = function(response) {
console.log(response.success);
alert( "failure message: " + JSON.stringify(response));
};
var data = { "mis": 111608059};
// data = JSON.stringify(data),
$http.post('api/stu_course_%.php', data).then(successCallback, errorCallback);
The above code gives the following error:
failure message: {"data":"\n\n400 Bad Request\n\nBad RequestYour browser sent a request that this server could not understand.Apache/2.4.18 (Ubuntu) Server at localhost Port 80\n\n","status":400,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api/stu_course_%.php","data":{"mis":111608059},"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request","xhrStatus":"complete"}
Server-side code in php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'config.php';
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
$json_request = file_get_contents('php://input');
$request = json_decode($json_request, true);
print_r( $request);
$MIS = $request["mis"];
//$MIS = 111608059;
$data = array();
$result1 = mysqli_query($conn, "select enrolled.course_id, course_code, course_name from enrolled LEFT OUTER JOIN courses ON enrolled.course_id=courses.course_id where MIS='$MIS'");
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)){
$query2 = "select count(course_id) as count from attendance_item group by course_id, MIS having (MIS='$MIS' and course_id='$row[course_id]') ";
$query3 = "select count(course_id) as total_count from lecture group by course_id having course_id='$row[course_id]'";
$result2 = mysqli_query($conn, $query2);
$result3 = mysqli_query($conn, $query3);
$count = mysqli_fetch_assoc($result2);
// print_r ($count);
$total_count = mysqli_fetch_assoc($result3);
// print_r ($total_count);
$percent = $count["count"]/$total_count["total_count"] *100;
// echo $percent;
$data = array_push_assoc($data, $row["course_name"], $percent);
}
// print_r($data);
$success = 1;
json_encode($data);
}
else{
$success = 0;
}
$response = array();
$response["success"] = $success;
$response["data"] = $data;
echo json_encode($response);
?>

Error while uploading picture from mobile

I'm uploading a picture, it works fine if I am using a computer but if I am using my phone it says:
Sorry, there was an error uploading your slip
<?php
if(isset($_POST["imagea"]) || isset($_POST["imageb"]) || isset($_POST["imagec"]) || isset($_POST["imaged"])){
$post_image = "";
if(isset($_POST["imagea"])){
$post_image = $paying[1];
}
else if(isset($_POST["imageb"])){
$post_image = $paying[2];
}
else if(isset($_POST["imagec"])){
$post_image = $paying[3];
}
else if(isset($_POST["imaged"])){
$post_image = $paying[4];
}
else if(isset($_POST["imagee"])){
$post_image = $paying[5];
}
else if(isset($_POST["imagef"])){
$post_image = $paying[6];
}
else if(isset($_POST["imageg"])){
$post_image = $paying[7];
}
else if(isset($_POST["imageh"])){
$post_image = $paying[8];
}
else if(isset($_POST["imagei"])){
$post_image = $paying[9];
}
else if(isset($_POST["imagej"])){
$post_image = $paying[10];
}
echo "uploading $post_image";
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["slip"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(1) {
// Check file size
if ($_FILES["slip"]["size"] > 5000000) {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, your file is too large.");';
echo " window.location.href = window.location.href;";
echo ' </script>';
$uploadOk = 0;
}
// Allow certain file formats
else if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, only JPG, JPEG, PNG & GIF or non empty files are allowed..");';
echo " window.location.href = window.location.href;";
echo ' </script>';
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, your file was not uploaded.");';
echo " window.location.href = window.location.href;";
echo ' </script>';
// if everything is ok, try to upload file
} else {
include "connect.php";
$mem_no = $_COOKIE['mem_no'];
$slip_id = get_slip_id() + 1;
//$paying = get_slip_rec($mem_no);
$today = date('y-m-d');
$slip_name = $mem_no."".$post_image;
$target_file = "uploads/$slip_name.jpg";
if (move_uploaded_file($_FILES["slip"]["tmp_name"], $target_file)) {
if(!slip_exisists("$target_file")){
$sql = "insert into table (slip_id,slip_name,poster,receiver,slip_status,slip_date) values($slip_id,'$slip_name','$mem_no','$post_image','pending','$today')" ;
$result = mysqli_query($conn,$sql);
}
echo "errorf ".mysqli_error($conn);
echo '<script type="text/javascript">';
echo 'alert("your deposit slip have been successfully uploaded please wait for your payment to be confirmed");';
echo " window.location.href = window.location.href;";
echo ' </script>';
} else {
echo ' <script type="text/javascript">';
echo ' alert("Sorry, there was an error uploading your slip.");';
echo " window.location.href = window.location.href;";
echo ' </script>';
}
}
}
function slip_exisists($slip_name){
include "connect.php";
$sql = "select * from slip where slip_name = $slip_name and slip_status = 'pending'";
$result = mysqli_query($conn,$sql);
if($result){
return true;
}
else{
return false;
}
}
function get_slip_id(){
include "connect.php";
$sql = "select slip_id from slip order by slip_id desc";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_array($result,MYSQLI_NUM);
return $row[0];
}
else{
return 1;
}
}
function get_slip_rec($mem_noi){
include "connect.php";
$sql = "select mem_no from pay_request, req_hist where paying member = '$mem_noi' and pay_request.request_code = req_hist.request_code";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_array($result,MYSQLI_NUM);
return $row[0];
}
else{
return '404';
}
}
}
?>

Sign in page accepting any password

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
}

Json working for certain vars but not for others

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. :/

Categories

Resources