AJAX not outputting correct thing - javascript

So I'm trying to call a php method from javascript so I can query a database and get the results into my js functionality. Currently, the 'console.log(output)' that is in my ajax is just outputting:
"array (size=1)
'action' => string 'getResults' (length=10)'"
Not really sure why it's doing this, it should be returning the query result which is just one entry from the database. Anyone have any idea? Any help is welcome! Thanks.
Part of my Javascript file:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
}
callPHP();
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
*/
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
//echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
Conn.php - this is all the connection info, * out for confidential reasons:*
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "***";
}
?>
MySQLDao.php - this file holds the querys:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>

I think you misunderstand how to ship data between javscript and php.
Your javascript should be posting with $.post() if you want to send an object or array of data.
Your php will recieve json from the javascript. You need to use php's json_decode function on it to make it useful to php.
If you want the output of your php script to be useful to javascript, you need to encode it with php's json_encode function before returning it to the calling script.
http://php.net/manual/en/function.json-decode.php

The output is for echo var_dump($_GET); I'm sure. I can tell because of the output format is a var_dump type. and the success part of your code does not have any output. I mean in this part else { //Decodes data, dont change ... the output has been commented out.
I noticed that you are using MySqli but some methods are MySql api like this part of the code
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
I assume this code is not complete and in debugging phase as I can see many incomplete methods and function calls.
Also try to use prepared statements with place holders for security.
It is a good practice to use ob_clean() before API output as any extra character will destroy the output data and format. However, you will not see errors. There are useful tools for API testing like Browsers Rest Client extensions. The best way for debugging is always debugging tools and frameworks like x-debug.
Do following changes to your code. Hope this helps!
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
$param=$_REQUEST['action'];
// echo var_dump($_GET);
/*
$handle = fopen("php://input", "rb");
$param = '';
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
*/
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
ob_clean();
echo json_encode($returnValue);
exit();
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
//Clean up before output
ob_clean();
echo json_encode($returnValue);
exit();
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
//Close connection as fast as possible
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode($result);
exit();
}
}
?>
MySQLDao.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = ?";
$stsm = $this->mysqli->prepare($sql);
$stsm->bind_param('i',1);
$result = $stmt->execute();
if (mysqli_num_rows($result) == 1) {
$obj = mysqli_fetch_object($result, 'obResults');
return $obj;
}
return false;
}
}
?>

Related

I keep getting this error in my code: Error: SyntaxError: Unexpected token 'o', "object(std"... is not valid JSON

Here is my php script for the registration page, the data is still being entered into the correct table but this problem is persistent.
Edit: I've seen comments asking for the javascript code, I've included it below the php code now.
`<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
main();
function main(){
require 'connectToDB.php';
// echo "\nreached the php file";
$response = array("code" => 0, "message" => "");
$request = file_get_contents('php://input');
$jsonRequest = json_decode($request);
var_dump($jsonRequest);
if (checkForExistingUser($conn, $jsonRequest) != 0){
$response["code"] = 2;
$response["message"] = "User already exists";
}
// else if($response["code"] == 1){
// // $userID = $conn->lastInsert();
// // header("Location: UniqueUserID.php");
// exit;
// }
else{
$response = addUser($conn, $jsonRequest);
// header("Location: UniqueUserID.php");
exit;
}
// printf(json_encode($response));
// var_dump($response);
$conn = null;
return json_encode($response);
}
function checkForExistingUser ($conn, $jsonRequest){
$stmt = $conn->prepare("
SELECT COUNT(Email) as noOfUsers
FROM user_main
WHERE Email = :confirmemailadd");
// $stmt -> bindParam(':confirmemailadd', $jsonRequest->confirmemailadd);
if (isset($jsonRequest->confirmemailadd)) {
$stmt->bindValue(':confirmemailadd', $jsonRequest->confirmemailadd);
} else {
$stmt->bindValue(':confirmemailadd', '');
}
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
$noOfResults = $results[0]["noOfUsers"];
// echo($noOfResults);
return $noOfResults;
}
function addUser($conn, $jsonRequest){
$response = array("code"=>0, "message"=>"");
// echo ("Reached addUser \n");
$firstname = sanitise($jsonRequest->firstname);
$surname = sanitise($jsonRequest->surname);
$username = sanitise($jsonRequest->username);
$confirmemailadd = sanitise($jsonRequest->confirmemailadd);
$phonenum = sanitise($jsonRequest->phonenum);
$retypepassword = sanitise($jsonRequest->retypepassword);
function encryptPassword($retypepassword) {
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($retypepassword, 'AES-256-CBC', $key, 0, $iv);
$hash = hash_hmac('sha256', $encrypted, $key);
return $hash . ':' . base64_encode($iv) . ':' . base64_encode($encrypted);
}
$stmt = $conn->prepare("
INSERT INTO user_main (Name, Surname, Username, Email, PhoneNum, PWD)
VALUES (:firstname, :surname, :username, :confirmemailadd, :phonenum, :retypepassword) ");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':surname', $surname);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':confirmemailadd', $confirmemailadd);
$stmt->bindParam(':phonenum', $phonenum);
$stmt->bindParam(':retypepassword', $retypepassword);
try{
$stmt->execute();
$userID = $conn->lastInsertId();
$response["code"] = 1;
$response["message"] = "successfully added";
$response["user_id"] = $userID;
}
catch (PDOException $e){
$response["code"] = 0;
$response["message"] = $e->getMessage();
}
// echo json_encode($response);
return $response;
}
function sanitise($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
`
I'm still relatively new to the back-end development side of things but I cannot figure this one out, I've tried to google it and research other solutions on stack overflow but couldn't find anything useful
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
}, false)
function handleFormSubmit(event) {
event.preventDefault();
checkEmails();
checkPasses();
processForm();
// redirectToPage()
}
function checkEmails(){
var emailValue = document.getElementById("emailadd").value;
var retypeEmailValue = document.getElementById("confirmemailadd").value;
if (emailValue !== retypeEmailValue){
window.alert("Emails do not match.");
}
}
function checkPasses(){
var passValue = document.getElementById("password").value;
var retypeValue = document.getElementById("retypepassword").value;
if (passValue !== retypeValue){
window.alert("Passwords do not match.");
}
}
function processForm(){
var userDetails = gatherData()
console.log(userDetails);
postRequest(userDetails)
}
function gatherData(){
//gather the data from the form fields into JSON
var userDetails = {
firstname : document.getElementById("firstname").value,
surname : document.getElementById("surname").value,
username : document.getElementById("username").value,
confirmemailadd: document.getElementById("confirmemailadd").value,
phonenum: document.getElementById("phonenum").value,
retypepassword: document.getElementById("retypepassword").value,
}
return userDetails;
}
async function postRequest(userDetails){
// make an AJAX POST request to server
try{
const response = await fetch("../php/register.php",{
method: 'POST',
headers: {
'Origin' : 'http://localhost/',
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
body: JSON.stringify(userDetails),
});
const data = await response.json();
console.log(data);
handleResponseCode(data);
}catch (error){
console.log('Error:',error);
}
}
function handleResponseCode(data){
console.log("response code: ", data.code);
console.log("response message: ", data.message);
if (data.code == 1){
alert ("Your account has been successfully created")
}
else if (data.code == 2 ){
alert (data.message );
}
}
You can try to catch the root cause of this error:
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
This will catch any exceptions thrown during the encoding process and allow you to handle them appropriately.
Edit:
function main(){
// ...
try {
$jsonResponse = json_encode($response);
} catch (Exception $e) {
// Handle JSON encoding error
die("JSON encoding error: " . $e->getMessage());
}
$conn = null;
return $jsonResponse;
}
you can put this catch error inside a function you wanna trace
Just remove the var_dump(...). Because that var_dump is already sending content back.

Ajax insert data not returning response - PHP & MySQL

I am working on a scanner reader, so I used ajax when the code is read by the scanner, it should insert data to the database. The problem is the data is not inserting.
Inside the script / Ajax - query is the variable I used to get the data (name)
var query = $('#scanned-QR').val();
fetch_customer_data(query);
$(document).on('keyup', '#scanned-QR', function(){
var query = $(this).val();
fetch_customer_data(query);
});
function fetch_customer_data(query = '')
{
$.ajax({
url:"validScan.php",
method: 'GET',
data:{query:query},
dataType: 'json',
success:function(data) {
console.log(data);
if (data.status == '1') {
decoder.stop();
alert('Sucess!');
}
else if(data.status=='0'){
decoder.stop();
alert('Fail!');
}
},
error:function(err){
console.log(err);
}
});
}
My Input/Textarea
<textarea id="scanned-QR" name="scanQR" readonly></textarea>
MySQL
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
}
mysqli_close($link);
?>
For insert query, result will return as boolean, So mysqli_num_rows($res) won't accept boolean argument. mysqli_num_rows() expects parameter 1 to be mysqli_result
So you can simply check by below, whether it is inserted or not:
if ($res) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose);
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose);
exit;
}
mysqli_close($link);
You should use exit try following code :
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
exit;
}
mysqli_close($link);
exit;
mysqli_num_rows() is for getting the number of rows returned from a SELECT query. You need to check the number of affected rows instead.
You should also be using a prepared statement, and I also recommend that you set up MySQLi to throw errors. I also prefer the object-oriented approach.
<?php
// Configure MySQLi to throw exceptions on failure
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Init connection
$link = new mysqli("localhost", "root", "", "schedule");
$response = [];
// Prepare the statement and execute it
$stmt = $link->prepare("INSERT INTO attendance (name) VALUES (?)");
$stmt->bind_param("s", $_GET['query']);
$stmt->execute();
// Check the number of inserted rows
if ($stmt->affected_rows) {
$response['status'] = 1;
} else {
$response['status'] = 0;
}
// Close the statement and connection
$stmt->close();
$link->close();
echo json_encode($response);

Query result in the error response in the JQuery function

I have a problem, clicking in a < tr > of a table I call a javascript function which in turn calls a function in php to get data in a database. The click on the table row works, sql works, and from the console.log command I know there is an answer in reponseText. but it does not work and I get the error back, I'll post the code. I hope you can help me.
file config.php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
file cards.php
<?php
class card
{
private $_db;
function __construct($db){
$this->_db = $db;
}
public function view_card_id($id)
{
$rows = array();
$statement = $this->_db->prepare('SELECT * FROM card_details WHERE card_id = :card_id');
$statement->execute(array(':card_id' => $id));
$numrows = $statement->fetch(PDO::FETCH_ASSOC);
if($numrows < 1) {
$this->error = "Error";
return false;
} else {
$statement->bindColumn("card_id", $cid);
$statement->bindColumn("a", $a);
$statement->bindColumn("b", $b);
$rows[] = array('card_id' => $numrows['card_id'], 'a' => $numrows['a'], 'b' => $numrows['b']);
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$row = array('card_id' => $cid, 'a' => $a, 'b' => $b);
$rows[] = $row;
}
return $rows;
}
}
file index.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
?>
html code ....
<script src="/js/Cards.js" type="text/javascript"></script>
file Cards.js
$('#table-cards tr').click(function() {
var id = $(this).find("a").text();
$.ajax({
type: 'POST',
url: '/classes/cardsFunc.php',
dataType:'text',
data: {functionname: "view_card", id: id },
success: function(response){
//Use response
alert("Server echo: "+response);
console.log(response);
},
error: function(msg){
console.log(msg);
alert("Error: "+msg);
}
});
});
In the Cards.js file, once the $ .ajax function is called, it does not return to success but to error, but in the console.log I see the array of the executed query under the responseText entry.
that is, in the error response, I see the result of the query, which in theory should be in the response of success.
I also tried to use
$.post('/classes/cardsFunc.php', { functionname: 'view_card', id: id }, function(data){
});
but nothing
file cardsFunc.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
thank you for the time you have dedicated to me
I noticed that if I recreate the connection to the db in the file cardsFunc.php, everything works, but I do not understand why, since everything is in the config.php file.
Like this:
file cardsFunc.php
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>

Call data back from AJAX

I have a script which saves canvas PNGs to a directory and I need the URL to save on the server.
When I submit, the image saves but the server remains empty. I am trying to return error messages but I am receiving nothing.
JAVASCRIPT:
function doodleSave() {
var drawing = document.getElementById("doodle-canvas");
var drawingString = drawing.toDataURL("image/png");
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST", 'http://www.website.com/php/doodleSave.php', true);
ajax.onreadystatechange= function() {
if (ajax.readyState === 4) //If it ran smoothly
{$("#doodle-submit-button").html("...");}
};
ajax.send(postData);
ajax.success(function(data) {
{$("#doodle-submit-button").html(""+data+"");}
});
}
PHP:
<?php
session_start();
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
$rawImage = $GLOBALS['HTTP_RAW_POST_DATA'];
$removeHeaders = substr($rawImage, strpos($rawImage, ",")+1);
$url = md5(uniqid(rand(), true));
$decode = base64_decode($removeHeaders);
$fopen = fopen('../images/external/doodles/'.$url.'.png', 'wb');
fwrite($fopen, $decode);
fclose($fopen);
//ADD POST TO DATABASE WITH USER'S ID
/* AUTOMATED VARIABLES */
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = 'images/external/doodles/'.$url;
try
{
$stmt = $pdo->prepare("INSERT INTO `(table name)` (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUES(:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$profile_unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "uploaded";
}
else
{
echo "Could not upload";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>

Call to undefined method mysqli_stmt::get_result() on line 43 [duplicate]

This question already has answers here:
Call to undefined method mysqli_stmt::get_result
(10 answers)
Closed 6 years ago.
I have a small problem. When I try to login on a script I worked on I can not login. I hope you guys can help me out. For some reason I get this MySQL error:
Call to undefined method mysqli_stmt::get_result() in
home/[username]/public_html/inc/session.php on line 43
The code for session.php:
<?php
class Session {
private $self_file = 'session.php';
private $mysqli = false;
public function __construct($m) { $this->mysqli = $m; }
public function isLogged() {
if(!isset($_SESSION['invento_logged']) || !is_array($_SESSION['invento_logged']))
return false;
if(!isset($_SESSION['invento_logged']['u']) || !isset($_SESSION['invento_logged']['p']))
return false;
$u = $_SESSION['invento_logged']['u'];
$p = $_SESSION['invento_logged']['p'];
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'isLogged()');
$this->execute($prepared, 'isLogged()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c == 1)
return true;
return false;
}
public function refresh_password($pass) {
$_SESSION['invento_logged']['p'] = md5($pass);
return true;
}
public function login($u, $p) {
$p = md5($p);
$prepared = $this->prepare("SELECT count(*) as c FROM invento_users WHERE username=? && password=?", 'isLogged()');
$this->bind_param($prepared->bind_param('ss', $u, $p), 'login()');
$this->execute($prepared, 'login()');
$result = $prepared->get_result();
$row = $result->fetch_object();
if($row->c != 1)
return false;
$_SESSION['invento_logged']['u'] = $u;
$_SESSION['invento_logged']['p'] = $p;
return true;
}
public function logout() {
if(isset($_SESSION['invento_logged']))
$_SESSION['invento_logged'] = false;
unset($_SESSION);
session_destroy();
return true;
}
public function get_user_id() {
$username = $_SESSION['invento_logged']['u'];
$prepared = $this->prepare("SELECT id FROM invento_users WHERE username=?", 'get_user_id()');
$this->bind_param($prepared->bind_param('s', $username), 'get_user_id()');
$this->execute($prepared, 'get_user_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->id;
}
public function get_user_name_by_id($id) {
$prepared = $this->prepare("SELECT username FROM invento_users WHERE id=?", 'get_user_name_by_id()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_name_by_id()');
$this->execute($prepared, 'get_user_name_by_id()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->username;
}
public function get_user_role() {
$id = $this->get_user_id();
$prepared = $this->prepare("SELECT role FROM invento_users WHERE id=?", 'get_user_role()');
$this->bind_param($prepared->bind_param('i', $id), 'get_user_role()');
$this->execute($prepared, 'get_user_role()');
$result = $prepared->get_result();
$row = $result->fetch_object();
return $row->role;
}
/***
* Private functions
*
***/
private function prepare($query, $func) {
$prepared = $this->mysqli->prepare($query);
if(!$prepared)
die("Couldn't prepare query. inc/{$this->self_file} - $func");
return $prepared;
}
private function bind_param($param, $func) {
if(!$param)
die("Couldn't bind parameters. inc/{$this->self_file} - $func");
return $param;
}
private function execute($prepared, $func) {
$exec = $prepared->execute();
if(!$exec)
die("Couldn't execute query. inc/{$this->self_file} - $func");
return $exec;
}
private function query($query, $func) {
$q = $this->mysqli->query($query);
if(!$q)
die("Couldn't run query. inc/{$this->self_file} - $func");
return $q;
}
public function __destruct() {
if(is_resource($this->mysqli) && get_resource_type($this->mysqli) == 'mysql link')
$this->mysqli->close();
}
}
$_session = new Session($mysqli);
and the code for config.php:
<?php
session_start();
/************ You can edit details starting from here ************/
$dbhost = '(I've filled this in'; // Write your MySQL host here.
$dbuser = 'I've filled this in'; // Write your MySQL User here.
$dbpass = 'I've filled this in'; // Write your MySQL Password here.
$dbname = 'I've filled this in'; // Write the MySQL Database where you want to install
/************ DON'T EDIT NOTHING BELOW ************/
if(!isset($noredir) && $dbhost == 'localhost' && $dbuser == 'MYSQL USERNAME' && $dbpass == 'MYSQL PASSWORD')
header('Location:install.php');
if(!isset($noredir)) {
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_errno)
die('<h2>Something went wrong while trying to connect to your MySQL Database. Error No. ' . $mysql->connect_errno.'<h2>');
// Check existance of random table to test installed system
$tables = array('users','categories','items','logs','settings');
$rn = rand(0,4);
$res = $mysqli->query("SHOW TABLES LIKE '%invento_{$tables[$rn]}%'");
if($res->num_rows == 0)
header('Location:install.php');
}
I hope you guys can help me out.
Thanks in advance,
Bram
I think it's because of the version of PHP that you are using.
As mentioned in php documentation mysqli_stmt::get_result, this method is supported since PHP 5.3.0.
And it is stated in the user notes section that:
This method requires the mysqlnd driver. Othervise you will get this error: Call to undefined method mysqli_stmt::get_result()
Instead of this function, try using bind_result function.
Helpful link
http://php.net/manual/en/mysqli-stmt.get-result.php

Categories

Resources