500 server error codeigniter ajax - php

I'm getting a 500 server error within the console when the ajax script is executed, and I'm not sure as to why. If I change the code up a bit to implement mysqli functions, and run these on my local machine everything works just fine, but as soon as I try to get this to work with codeigniter, I get the 500 server error.
Here is my code:
<?php
class Phonecall extends CI_Controller {
public function index() {
/*$con = mysqli_connect('localhost','root','root','MYDB');
if (!$con) {
die ('Could not connect: ' . mysqli_error($con));
}*/
//$operatorId = $_SESSION['Oper']['OperatorID'];
//$sql = "SELECT phone_number FROM incoming_calls WHERE OperatorID='${operatorId}'";
//$result = mysqli_query($con,$sql);
$query = $this->db->query("SELECT phone_number FROM MYDB.incoming_calls");// WHERE OperatorID='${operatorId}'");
while ($row = $query->row_array()) {
$number = $row['phone_number'];
}
/*$sql = "SELECT Username, UserID, Name
FROM tblUsers
WHERE PhoneHome='999-999-9999' OR PhoneCell='999-999-9999' OR PhoneWork='999-999-9999'";
*/
$query = $this->db->query("SELECT Username, UserID, Name
FROM MYDB.tblUsers
WHERE PhoneHome='999-999-9999' OR PhoneCell='999-999-9999' OR PhoneWork='999-999-9999'");
while ($row = $query->row_array()) {
$userArray[] = array("name" => $row['Name'], "username" => $row['Username'], "user_id" => $row['UserID']);
}
if (!empty($userArray)) {
echo json_encode($userArray);
}
if (isset($_POST["drop"])) {
$query = $this->db->query("DELETE FROM MYDB.incoming_calls
WHERE phone_number = $number
LIMIT 1");
if (!$result) {
die ('Could not drop row: ');
}
}
$this->db->close();
}
}
?>
Here is the ajax call that retrieves the information:
var user = new Array();
var user_id = new Array();
var name = new Array();
$.get(baseURL + 'phonecall/index', function(data) {//where baseURL is defined
var loginInfo = jQuery.parseJSON(data);
for (var i = 0; i < loginInfo.length; ++i) {
name[i] = loginInfo[i].name;
user[i] = loginInfo[i].username;
user_id[i] = loginInfo[i].user_id;
}
}
Does anyone know as to why this would happen?

Related

data being pulled in from mysql but cant pass it to html via ajax

I am using a php file to pull data from a mysql database and then pushing it through to a html page using Ajax:
the data is being pulled in correctly and it looks to be pushed through as it shows in the network tab (response) but when i look in the console log there is nothing showing any ideas why
php
<?php
header('Content-type: application/json');
$servername = "test:3306";
$username = "test";
$password = "test!";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = "SELECT beacon,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon ";
$result = $conn->query($sql);
$sql2 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result = $conn->query($sql2);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$result2 = mysqli_query($conn , $sql2);
$rows2 = array();
while($r = mysqli_fetch_assoc($result2)) {
$rows2[] = $r;
}
echo json_encode($rows2);
$conn->close();
?>
html
<script>
$(document).ready(function() {
for (var i = 0; i < 12; i++) {
var row = $('<tr>').appendTo("#zoning tbody");
for (var j = 1; j < 11; j++) {
$(`<td class='${i * 10 + j}'>${i * 10 + j}</td>`).appendTo(row);
}
}
$.get('php/test.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item.delivery_avg,item.beacon,item.location);
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
});
});
function updateTable() {
//console.log('function called');
$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$.get('php/test.php', function(response) {
response.forEach(function(item, index) {
console.log(item.delivery_avg,item.beacon,item.location);
//$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$(`td.${item.beacon}`).css('background-color', item.location).toggleClass('coloured');
if (item.delivery_avg <= 10.00) {
return $(`td.${item.beacon}`).css({'border-color':'lime', 'border-width':'thick'}).toggleClass('coloured');
} else if (item.delivery_avg>= 10.01 && item.delivery_avg <= 20.00) {
return $(`td.${item.beacon}`).css({'border-color':'orange', 'border-width':'thick','background-color':item.location}).toggleClass('coloured');
} else if (item.delivery_avg>= 20.01 && item.delivery_avg <= 30.00) {
return $(`td.${item.beacon}`).css({'border-color':'pink', 'border-width':'thick','background-color':item.location}).toggleClass('coloured');
}
});
});
}
var updateTableInterval = setInterval(updateTable, 2000);
});
</script>

live visitor counter for single page

I'm current working on a live leader-board page and i am trying to add a live view counter to it. I am not getting and data sent to the database and its not reading from the database. I have checked the db connection and its working. I have checked the code in php tester and it has no errors.
Take a look and let me know what i missed, Thanks
class VisitorCounterReal {
var $sessionTimeInMin = 5; // time session will live, in minutes
function VisitorCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$this->cleanVisitors();
if ($this->visitorExists($ip))
{
$this->updateVisitor($ip);
} else
{
$this->addVisitor($ip);
}
}
function visitorExists($ip) {
$query = "SELECT * FROM counter WHERE ip = '$ip'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) > 0)
{
return true;
} else
if (mysqli_num_rows($res) == 0)
{
return false;
}
}
function cleanVisitors()
{
$sessionTime = 30;
$query = "SELECT * FROM counter";
$res = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($res))
{
if (time() - $row['lastvisit'] >= $this->sessionTimeInMin * 60)
{
$dsql = "delete from counter where id = $row[id]";
mysqli_query($dsql);
}
}
}
function updateVisitor($ip)
{
$query = "UPDATE counter SET lastvisit = '" . time() . "' WHERE ip =
'$ip'";
mysqli_query($connection, $query);
}
function addVisitor($ip)
{
$query = "INSERT INTO counter(ip, lastvisit) ";
$query .= "VALUES('$ip', '" . time() . "') ";
mysqli_query($connection, $query);
}
function getAmountVisitors()
{
$query = "SELECT COUNT(id) FROM counter";
$res = mysqli_query($connection, $query);
$row = mysqli_fetch_row($res);
return $row[0];
}
function show()
{
echo '<h3>There is ' . $this->getAmountVisitors() . ' watching
online</h3>';
}
}
This is on the live leaderboard page below
<?php
$counter = new VisitorCounterReal; // make a new counter
//content here
$counter->show(); // show the counter
// and here
?>

codeigniter mysql queries don't work

I know this isn't good practice to have the queries within a controller, but for some reason they do not work within this controller class. I'm not too experienced with codeigniter, so any help is appreciated, as I have no idea on how else to set this up to work properly. I have an ajax script that gets the information.
Here is my code:
<?php
class Phonecall extends CI_Controller {
public function index() {
/*$con = mysqli_connect('localhost','root','root','MYDB');
if (!$con) {
die ('Could not connect: ' . mysqli_error($con));
}*/
//$operatorId = $_SESSION['Oper']['OperatorID']; //I also cannot figure out how to get $_SESSION information either
//$sql = "SELECT phone_number FROM incoming_calls WHERE OperatorID='${operatorId}'";
//$result = mysqli_query($con,$sql);
$query = $this->db->query("SELECT phone_number FROM MYDB.incoming_calls");// WHERE OperatorID='${operatorId}'");
while ($row = $query->row_array()) {
$number = $row['phone_number'];
}
/*$sql = "SELECT Username, UserID, Name
FROM tblUsers
WHERE PhoneHome='999-999-9999' OR PhoneCell='999-999-9999' OR PhoneWork='999-999-9999'";
*/
$query = $this->db->query("SELECT Username, UserID, Name
FROM MYDB.tblUsers
WHERE PhoneHome='999-999-9999' OR PhoneCell='999-999-9999' OR PhoneWork='999-999-9999'");
while ($row = $query->row_array()) {
$userArray[] = array("name" => $row['Name'], "username" => $row['Username'], "user_id" => $row['UserID']);
}
if (!empty($userArray)) {
echo json_encode($userArray);
}
if (isset($_POST["drop"])) {
$query = $this->db->query("DELETE FROM MYDB.incoming_calls
WHERE phone_number = $number
LIMIT 1");
if (!$result) {
die ('Could not drop row: ');
}
}
$this->db->close();
}
}
?>
Here is my JS:
var user = new Array();
var user_id = new Array();
var name = new Array();
$.get(baseURL + 'phonecall/index', function(data) {//where baseURL is defined
var loginInfo = jQuery.parseJSON(data);
for (var i = 0; i < loginInfo.length; ++i) {
name[i] = loginInfo[i].name;
user[i] = loginInfo[i].username;
user_id[i] = loginInfo[i].user_id;
}
}
I do not know much about frameworks and I'm trying to learn, I also do not know how to make this file access the $_SESSION data. Any help is greatly appreciated.
Always use model for DB queries.
For first query use the following code:
$this->db->select("phone_number");
$this->db->from("incoming_calls");
$query = $this->db->get();
return $query->result_array();
For the secound query use this:
$this->db->select("Username, UserID, Name");
$this->db->from("tblUsers");
$this->db->where("PhoneHome,'999-999-9999'");
$this->db->where("PhoneCell,'999-999-9999'");
$this->db->where("PhoneWork,'999-999-9999'");
$query = $this->db->get();
return $query->result_array();
Be sure to make 2 different functions for the queries in model.
Then at your controller side use the following code:
$data['first_record'] = $this->your_modal_name->your_first_function_name();
$data['secound_record'] = $this->your_modal_name->your_second_function_name();
Then run this data in foreach, and it will give you the record, which you want.

Errors when adding data to a database with PHP

I have to make a web app that gets information from my database, that gets its info from an API). Then I have to show items under certain conditions.
But when I try to add the data from the API, I got a strange message:
Notice: Trying to get property of non-object in c:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Here is my PHP code:
<?php
require_once 'settings.php';
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_database);
if (mysqli_connect_error()) {
echo mysqli_connect_error($mysqli) . "We are not able to connect to the online database";
}
jsondecode($mysqli);
if (isset($_GET['club']) && !empty($_GET['club'])) {
jsondecode($mysqli);
} else if (isset($_GET['thuisPoint']) && !empty($_GET['thuisPoint']) && ($_GET['uitPoint']) && ($_GET['uitPoint'])) {
updatePoints($mysqli);
} else {
getWedstrijd($mysqli);
}
function jsondecode($mysqli) {
$apiLink = 'http://docent.cmi.hr.nl/moora/imp03/api/wedstrijden?club=';
// $club = $_GET['club'];
$data = json_decode(file_get_contents($apiLink . "Ajax"));
foreach ($data->data as $info) {
$thuisClub = $info->homeClub;
$uitClub = $info->awayClub;
addWestrijden($mysqli, $thuisClub, $uitClub);
}
}
//querys
function addWestrijden($mysqli, $thuisClub, $uitClub) {
$query = "INSERT INTO wedstrijd VALUES(null, '$thuisClub', '$uitClub')";
$resultAddWedstrijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
function getWedstrijd($mysqli) {
$query = "SELECT * FROM wedstrijd ORDER BY thuisClub DESC";
$resultGetWedstijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
while ($result = mysqli_fetch_assoc($resultGetWedstijd)) {
$rows [] = $result;
}
header("Content-Type: application/json");
echo json_encode($rows);
exit;
}
function updatePoints($mysqli) {
$id = $_GET['id'];
$thuisPoints = $_GET['thuisPoint'];
$uitPoints = $_GET['uitPoint'];
$query = "UPDATE wedstrijd "
. "SET thuisPunt = '$thuisPoints', uitPunt = '$uitPoints') "
. "WHERE id = '$id'";
mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
I did modify it a bit so it would add data from the API. I really would appreciate it if someone could help me.
Change your foreach to:
foreach ($data as $data => $info)

Fatal error: Call to a member function query() on a non-object in .php file

I'm new to PHP and SQL, but I'm trying to create a login script for my webapp.
For some reason I'm stuck. When the username or password-field is empty, there is an alert, but when they are both filled in correct or incorrect, there is no alert.
When I open the website in my browser (Chrome) and inspect the page, I get:
"POST ../App/auth.php 500 (Internal Server Error)"
When I open the error.log-file from my server, I get:
"PHP Fatal error: Call to a member function query() on a non-object in ../App/class.manageUsers.php on line 24, referer: ../App/login.php"
line 24 in class.manageUsers.php is:
$query = $this->link->query("SELECT * FROM users WHERE username = '$username' AND
password = '$password' LIMIT 1");
class.manageUsers.php:
<?php
include_once('class.database.php');
class ManageUsers{
protected $link;
function __construct(){
$db_conn = new ManageDatabase;
$this->link = $db_conn->connect();
return $this->link;
}
function addUsers($username,$firstname,$lastname,$email,$password,$user_level){
$query = $this->link->prepare("INSERT INTO users (username,firstname,lastname,email,password,user_level)
VALUES (?,?,?,?,?,?)
");
$values = array($username,$firstname,$lastname,$email,$password,$user_level);
$query->execute($values);
$rowCount = $query->rowCount();
return $rowCount;
}
function loginUsers($username,$password){
$query = $this->link->query("SELECT * FROM users WHERE username = '$username' AND password = '$password' LIMIT 1");
$rowCount = $query->rowCount();
return $rowCount;
}
function listUsers($user_id = null){
if(isset($user_id))
{
$query = $this->link->query("SELECT * FROM users WHERE id = '$user_id' LIMIT 1");
}
else
{
$query = $this->link->query("SELECT * FROM users ORDER BY id DESC");
}
$rowCount = $query->rowCount();
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
}
function editUsers($user_id,$param){
foreach ($param as $key => $value)
{
$query = $this->link->query("UPDATE users SET $key = '$value' WHERE id = '$user_id' LIMIT 1");
}
$rowCount = $query->rowCount();
return $rowCount;
}
function deleteUsers($user_id){
$query = $this->link->query("DELETE FROM users WHERE id = '$user_id' LIMIT 1");
$rowCount = $query->rowCount();
return $rowCount;
}
}
?>
class.database.php:
<?php
class ManageDatabase{
protected $db_conn;
protected $db_host = 'localhost';
protected $db_name = 'jqueryMobile';
protected $db_user = 'root';
protected $db_pass = '';
function connect(){
try{
$this->db_conn = new PDO("mySQL:host=$this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
}
catch(PDOexception $e){
return $e->getMessage();
}
}
}
?>
I hope someone can find where it seems to go wrong.
Thanks.
As far as I can see, direct reason for error is empty 'link' property. Looks like dbmanager class failed when connecting to db. That would explain why query method cannot be called.

Categories