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
Related
I'm trying to asynchronously upload a file via javascript in the background. I'm updating our library to use fetch instead of XHR. The XHR request works correctly and the network tab shows the expected response which is currently just a var_dump($_FILES) and a var_dump($_POST).
When I make the same call with fetch for some reason the PHP stops running on the session creation.
I've isolated it down to the line:
$session = new Session;
Here is a cleaned up version of the XHR which returns both of those PHP arrays populated correctly
var request = {},
url = "../../lib/upload.php",
formData = new FormData;
formData.append(
"PHP_SESSION_UPLOAD_PROGRESS", phpSessionKey // upload session key var
);
formData.append(
"uploaded_file", this.file.baseFile // file object from an upload input
);
formData.append(
"pageid", 1234
);
request = new XMLHttpRequest();
request.open("POST", url, true);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
console.log(responseText);
}
}
request.send(formData);
Here is the comparable fetch, mind you I've looked at headers and everything else which all seem to be identical but I can not figure out why the fetch version exits on that session creation line.
let formData = new FormData(),
phpSessionKey = Uploader.pageid + "_" + this.file.name,
that = this;
formData.append(
"PHP_SESSION_UPLOAD_PROGRESS", phpSessionKey
);
formData.append(
"uploaded_file", this.file.baseFile
);
formData.append(
"pageid", Uploader.pageid
);
fetch('../lib/upload.php', {
method: 'POST',
body: formData
});
This fetch in the network tab returns nothing and by going in and comment then uncommenting lines I've narrowed the issue down to the session creation line in upload.php. I'm honestly just confused about why this is happening at this point, trying to bring out JS standards up has been pretty smooth sailing until now.
EDIT
Here is the session class in PHP:
class Session {
private $user_id;
private $last_login;
private $database;
public $user;
public $username;
public const MAX_LOGIN_AGE = 60 * 60 * 24; // 1 day
// Constructor which attaches pseudo magic methods to php sessions
public function __construct()
{
session_set_save_handler(
array($this, '_open'),
array($this, '_close'),
array($this, '_read'),
array($this, '_write'),
array($this, '_destroy'),
array($this, '_clean')
);
session_start();
$this->check_stored_login();
}
public function _open()
{
if ($session_db = db_connect(DB_DEV)) {
$this->database = $session_db;
return true;
}
return false;
}
public function _close()
{
// print "Session closed.\n";
return $this->database->close();
}
public function _read($id)
{
$id = $this->database->escape_string($id);
// print "Session read.\n";
// print "Sess_ID: $id\n";
$sql = "SELECT data
FROM sessions
WHERE id = '{$id}'";
if ($result = $this->database->query($sql)) {
if ($result->num_rows) {
$record = $result->fetch_assoc();
return $record['data'];
}
}
return '';
}
public function _write($id, $data)
{
$access = time();
$id = $this->database->escape_string($id);
$access = $this->database->escape_string($access);
$data = $this->database->escape_string($data);
// print "Session value written.\n";
// print "Sess_ID: $id\n";
// print "Data: $data\n\n";
$sql = "REPLACE
INTO sessions (`id`, `access`, `data`)
VALUES ('{$id}', '{$access}', '{$data}')";
$this->database->query($sql);
return true;
}
public function _destroy($id)
{
$id = $this->database->escape_string($id);
// print "Session destroy called.\n";
$sql = "DELETE
FROM sessions
WHERE id='{$id}'";
return $this->database->query($sql);
}
public function _clean($max)
{
$old = $time() - $max;
$this->database->escape_string($old);
$sql = "DELETE
FROM sessions
WHERE access < '{$old}'";
return $this->database->query($sql);
}
public function login($user)
{
if ($user) {
// prevent session fixation attacks
session_regenerate_id();
$this->user_id = $_SESSION['user_id'] = $user->id = $user->id;
$this->username = $_SESSION['username'] = $user->first_name;
$this->last_login = $_SESSION['last_login'] = time();
$this->user = $_SESSION['user'] = $user;
$_SESSION['search_text'] = '';
$_SESSION['search_product_id'] = '';
$args["last_login"] = date("Y-m-d H:m:s");
$user->merge_attributes($args);
$user->save();
}
}
public function is_logged_in()
{
if (!isset($this->user_id) || !$this->last_login_recent()) {
redirect_to(url_for('/index.php?logout'));
}
return true;
}
public function logout()
{
unset($_SESSION['user_id']);
unset($_SESSION['username']);
unset($_SESSION['last_login']);
unset($_SESSION['user']);
unset($this->user_id);
unset($this->username);
unset($this->last_login);
unset($this->user);
session_destroy();
return true;
}
private function check_stored_login()
{
if (isset($_SESSION['user_id'])) {
$this->user_id = $_SESSION['user_id'];
$this->username = $_SESSION['username'];
$this->last_login = $_SESSION['last_login'];
$this->user = $_SESSION['user'];
}
}
private function last_login_recent()
{
if (!isset($this->last_login)) {
return false;
} elseif ($this->last_login + self::MAX_LOGIN_AGE < time()) {
return false;
} else {
return true;
}
}
public function message($msg = '')
{
if (!empty($msg)) {
$_SESSION['message'] = $msg;
} else {
return $_SESSION['message'];
}
}
}
?>
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;
}
}
?>
I have an AngularJS application that I am updating to use PHP 7. Currently I have a custom session handler setup for sessions:
Custom Session Handler (session.php)
function sess_open( $path, $name ) {
return true;
}
function sess_close( ) {
$sessionId = session_id();
return true;
}
function sess_read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
return $data;
}
function sess_write( $id, $data ) {
$db = dbConn::getConnection();
$tstData = sess_read( $id );
if (!is_null($tstData)) {
// if it does then do an update
$stmt = "UPDATE session SET session_data =" . $db->quote($data) . " WHERE session_id=" . $db->quote($id);
$db->query($stmt);
}
else {
// else do an insert
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ")";
$db->query($stmt);
}
return true;
}
function sess_destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
return $db->query($stmt);
}
function sess_gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
return $db->query($stmt);
}
session_name('PROJECT_CUPSAW_WEB_APP');
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
ob_flush();
In my app.js I have a continuous check to see if the user is authenticated and can access the application.
App.js
/*
* Continuous check for authenticated permission to access application and route
*/
app.run(function($rootScope, $state, authenticationService, ngToast) {
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
authenticationService.isAuthenticated()
.success(function () {
if(toState.permissions) {
ngToast.dismiss();
event.preventDefault();
$state.go("logout"); // NEEDS TO CHANGE - Unauthorized access view
return;
}
})
.error(function () {
ngToast.dismiss();
event.preventDefault();
localStorage.clear();
$state.go("authentication"); // User is not authenticated; return to login view
return;
});
ngToast.dismiss();
});
});
In the code above, isAuthenticated runs isUserAuthorized.php
isAuthenticated
/*
* Check if user is authenticated; set role/permissions
*/
this.isAuthenticated = function() {
return $http.post(baseUrl + '/isUserAuthorized.php');
};
isUserAuthorized.php
<?php
require_once 'session.php';
// Check to ensure user is authenticated to initiate request
if (array_key_exists('authenticated', $_SESSION) && $_SESSION['authenticated']) {
return http_response_code(200);
} else {
// Clear out all cookies and destroy session
if( array_key_exists('HTTP_COOKIE', $_SERVER)){
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
session_destroy();
return http_response_code(401);
}
The session should be started when session.php is required. It appears that this is not happening though. Upon accessing the application, the login page is displayed, but isUserAuthorized.php is throwing a warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
When I select the Login button, login.php is called, but the user gets brought right into the application, despite incorrect credentials.
login.php
<?php
require_once '../database.php';
require_once 'session.php';
require_once 'ldap.php';
$_SESSION['authenticated'] = false;
//$conn = connect_db();
try {
$data = json_decode(file_get_contents('php://input'));
$username = strtolower($data->username);
$password = $data->password;
// Check domain credentials; return user token if verified
if(ldap_authenticate($username, $password)) {
$_SESSION['authenticated'] = true;
}
else {
echo('Invalid username and/or password!');
return http_response_code(400);
}
}
catch(PDOException $e) {
return http_response_code(400);
}
I'm not entirely sure what's causing this odd behavior, and why the session isn't being created. Do I need to explicitly call the sess_write function?
Update
I discovered that removing the require_once 'session.php' from login.php causes the proper behavior. The user is able to login when they provide valid credentials. However, the session data is still never being written to the database. Any idea why?
The issues came down to my session handler. As of PHP 7, the sess_read function must return a string. This was causing the warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
I fixed this by returning '' when $data was null.
This caused issues with my sess_write function knowing when to insert and when to update. I fixed this by changing the SQL.
Ultimately I ended up making the session handler a class, as shown in the final result:
<?php
require_once ('../database.php');
class CustomSessionHandler implements SessionHandlerInterface{
public function open( $path, $name ) {
return true;
}
public function close( ) {
return true;
}
public function read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
if(!$data){
return '';
}
return $data;
}
public function write( $id, $data ) {
$db = dbConn::getConnection();
//Works with Postgres >= 9.5
//$stmt = "INSERT INTO session (session_id, session_data) VALUES (" . $db->quote($id) . ", " . $db->quote($data) . ") ON CONFLICT (session_id) DO UPDATE SET session_data=" . $db->quote($data) . ";";
//Works with Postgres < 9.5
$stmt = "UPDATE session SET session_data=" . $db->quote($data) . " WHERE session_id=" . $db->quote($id) . ";";
$db->query($stmt);
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ");";
$db->query($stmt);
return true;
}
public function destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
$data = $db->query($stmt);
return true;
}
public function gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
$data = $db->query($stmt);
return true;
}
}
session_name('PROJECT_CUPSAW_WEB_APP');
$handler = new CustomSessionHandler();
session_set_save_handler($handler, false);
session_start();
ob_flush();
I have an input box in html. The input searches an database through ajax and return the results in front-end. The problem is that I don't get the result from PHP. I don't know what I did wrong, so I hope you guys have a better understanding from me.
HTML
<body onload="AjaxFindPerson()">
.....
</body>
JS
var xmlHttp = createXmlHttpRequestObject();
function AjaxFindPerson() {
if ((xmlHttp.readyState == 0 || xmlHttp.readyState == 4) && document.getElementById("PersonSearchInput").value != "") {
person = encodeURIComponent(document.getElementById("PersonSearchInput").value);
xmlHttp.open("GET", "../lib/search.php?email=" + person, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else {
document.getElementById('Label-Result').innerHTML = "";
document.getElementById('UserNameSearchResult').innerHTML = "";
$('#add-person-btn').attr("disabled", "disabled");
setTimeout('AjaxFindPerson()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 ) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
result = xmlDocumentElement.firstChild.data;
if (result[0] != false) {
document.getElementById('Label-Result').innerHTML = result[1];
document.getElementById('UserNameSearchResult').innerHTML = result[0];
$('#add-person-btn').removeAttr("disabled", "disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result[1];
}
setTimeout('AjaxFindPerson()', 1000);
}
else {
alert('Somenthing went wrong when tried to get data from server'+ xmlHttp.readyState);
}
}
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
session_start();
define("DB_HOST", 'mysql6.000webhost.com');
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_DATABSE", '');
echo '<response>';
$email = $_GET['email'];
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABSE, $conn);
$sq = mysql_query("SELECT UserEmail FROM Users");
$UserInfo = array();
while ($row = mysql_fetch_array($sq, MYSQL_ASSOC)) {
$UserInfo[] = $row['UserEmail'];
}
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
$returnRes = array($row[0], "We found results"); //row[0] holds the UserN
echo $returnRes;
}
else {
$returnRes = array(false, "We couldn't find results");
echo $returnRes;
}
echo '</response>';
?>
If we check the php-xml file alone will see the image bellow :
Do I need to pass the values to xml-php with another way?
UPDATE 1 in PHP
I manage to found a way to return the data correctly. Here are the update 'touch'
header('Content-Type: application/json');
and
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
echo json_encode(array( 'found' => $row[0], 'msg' => "We found results"));
}
else {
echo json_encode(array( 'found' => null, 'msg' => "We couldn't find results"));
}
The problem now is how to manipulate the js file to handle the return array. I made a try but it didn't worked:
result = xmlDocumentElement.firstChild.data;
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
**UPDATE 2 WORKING JS **
I figure out how to retrieve the data from PHP.
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
var result = JSON.parse(xmlDocumentElement.firstChild.data);
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
NOW ALL THE CODE IS WORKING! THANK YOU VERY MUCH GUYS!
+1 to all of you!
Four things :
Usage of send(null) doesn't seems to be right, just don't pass null in it.
Second one is timeout method. Instead the way you are using it, you can call it in the callback function or instead of string use the name at the function call.
The usage to remove the attribute is also wrong. It is currently using a set method as you have supplied a second argument. The remove attribute method only takes a attribute name.
I would rather suggest you to set a header for the application/json and use json_encode() method to return data.
For printing an array, you can either use json_encode(), or do somehow else transform your array into a string.
If we were to ignore the white elephant in the room and gloss over the use of mysql_* functions then a slightly different approach
<?php
session_start();
define('DB_HOST', 'mysql6.000webhost.com');
define('DB_USER', '');
define('DB_PASSWORD', '');
define('DB_DATABASE', '');
$dom=new DOMDocument('1.0','utf-8');
$root=$dom->createElement('response');
$dom->appendChild( $root );
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['email'] ) ){
/* Basic filtering IF mysql_* functions are used! */
$email = trim( strip_tags( filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL ) ) );
$conn = mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
mysql_select_db( DB_DATABASE, $conn ) or die('error: database connection failed');
/* By the looks of the original there should be no need for two queries and then an array lookup */
$result = mysql_query("SELECT `UserName` FROM `Users` WHERE `UserEmail` = '".$email."';");
/* If there are results, add nodes to the dom object */
if( mysql_num_rows( $result ) > 0 ){
while( $rs=mysql_fetch_object( $result ) ){
$root->appendChild( $dom->createElement( 'user', $rs->UserName ) );
}
} else {
/* Otherwise add error message */
$root->appendChild( $dom->createElement( 'error', 'We couldn\'t find any results!' ) );
}
}
/* Send the xml back to the js client */
header('Content-Type: text/xml');
$xml=$dom->saveXML();
$dom=null;
exit( $xml );
?>
I am using ajax to login user but this script is not working. When i call login function to execute nothing happens..
function login() {
var login = new XMLHttpRequest;
var e = document.getElementById("email").value;
var p = document.getElementById("password").value;
var vars = "email=" + e + "&password=" + p;
login.open("POST", "http://example.com/app/login.php", true);
login.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
login.onreadystatechange = function(){
if (login.readyState == 4 && login.status == "200") {
var response = login.responseText;
//document.getElementById("status").innerHTML = response;
}
document.getElementById("status").innerHTML = "Loggin in....";
login.send(vars);
if (response == "Sucess") {
window.location.replace("/logged.html");
}
else {
document.getElementById("status").innerHTML == "Login Failed";
}
}
}
login.php contains following codes
require_once('../db_/connection.php');//Holds connection to database
$email = mysqli_real_escape_string($con, $_POST['email']);//Sanitizing email
$pass = md5($_POST['password']);//Hashing password
$sql = "SELECT id FROM users WHERE email='$email' AND password='$pass' LIMIT 1";
$query = mysqli_query($con, $sql);
$check = mysqli_num_rows($query);
if($check < 1){
echo "fail";
//mysqli_close($con);
exit();
}
else{
echo "Sucess";
//mysqli_close($con);
exit();
}
Calling login function does not execute the code.
Line 2: The parentheses are missing after new XMLHttpRequest
Line 15: Your if (response == "Sucess") { ... } is misspelled and it gets executed before the ajax request is returned, because it's asynchronous
I made a working version at JSFiddle for you: http://jsfiddle.net/eRv83/
You might find the MDN referrence helpfull: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest