i have this model function for counting the number of users
public function get_employee_list($role_id) {
$qStr = "SELECT
count(admins.id)
FROM
admins
WHERE
admin_role=".$role_id;
$query = $this->db->query($qStr);
return $query->row_array();
}
and my controller function is like this
public function delete_employee_role_ajax($role_id) {
$objResponse = new xajaxResponse();
$response = $this->employee_model->get_employee_list($role_id);
//print_r($response);
if($response) {
$objResponse->script( "bootbox.alert('$response +users are associated with this role and it cannot be deleted')" );
}
else {
$response = $this->employee_model->delete_employee_role($role_id);
$objResponse->script( "window.location.reload()" );
}
return $objRespons
}
i want to print the value of $response.
You could try encoding it as a JSON structure:
$encodedResponse = json_encode($response);
$objResponse->script("bootbox.alert('$encodedResponse +users are associated...')" );
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'];
}
}
}
?>
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
I have a drop down box with multiple select . The dropdown looks like this:
<select multiple class="form-control" name="batch_no[]" id="batch_no" required onchange="getBatchCourseDetail();">
<option value="">-----------Select Your Batch----------</option>
<?php
foreach ($result as $res)
{
?>
<option value="<?php echo $res['batch_code']; ?>"><?php echo $res['batch_code']; ?></option>
<?php
} ?>
</select>
In onchange function call i have the script like this:
function getBatchCourseDetail()
{
var other = String($('#batch_no').val());
var opts = [],
opt;
var split1 = other.split(',');
for (var i = 0; i < split1.length; i++)
{
opt = split1[i];
opts.push(opt);
}
$.ajax({
url: 'course_apply_batch_course_detail_ajax.php',
type: 'POST',
data:
{
batch_code: opts
},
success: function (data)
{
//console.log(data);
$('#batch_information_autofill').html(data);
}
});
}
In the ajax file that is in course_apply_course_detail_ajax.php page I retrieve all the values of the drop down .
course_apply_course_detail_ajax.php :
<?php
require('classes/autoloader.php');
$course_apply = new \Model\CourseApplyModel();
$batch_code111=array();
$batch_code111 = $_POST['batch_code'];
$batch_code1 ="'" .implode("','",$batch_code111) ."'";
$parameter = array(
"batchcode" => $batch_code1,
"status" => 0);
$result11 =$course_apply->getBatchCourseDetail11($parameter);
echo"<pre>";
print_r($result11);
echo"</pre>";
exit;
?>
I will be getting the $batch_code1 values as : 'LATS-CHMB-1000','LATS-SA-1000','LATS-ABSE-1003' which is stored in the array variable 'batchcode'.
In Model My query looks like this:
public function getBatchCourseDetail11($parameter)
{
/* $QUERY1="SELECT start_date,end_date,course_code FROM batch WHERE
batch_code IN('LATS-CHMB-1000','LATS-SA-1000','LATS-ABSE-1003') AND status =0"; */
$query1="SELECT start_date,end_date,course_code FROM batch WHERE status =:status AND batch_code IN(:batchcode)";
try{
$result1=$this->dbh->prepare($query1);
$result1->execute($parameter);
$data11=$result1->fetchAll(\PDO::FETCH_ASSOC);
return $data11;
}
catch(\PDOException $e)
{
print_r($e);
return false;
}
}
When i try to print the return data i'm getting array() but the query is executing correctly in the phpmyadmin.
Thanks in advance please help me to get solved from this issue.
The query is your issue
$query1="SELECT start_date,end_date,course_code
FROM batch
WHERE status =:status
AND batch_code IN(:batchcode)";
it is not possible to substitute an arbitrary query part with a placeholder. So for a comma-separated placeholders, like IN(), you must create a set of ?'s manually and put them into the query:
In short we must create a syntax like IN(?,?,?) if you have 3 values you want in your IN() list and then pass the 3 paremeters to the prepare.
public function getBatchCourseDetail11($parameter)
{
// generate the number of ? we need
$ins = str_repeat('?,', count($parameter['batchcode']) - 1) . '?';
$query1="SELECT start_date,end_date,course_code
FROM batch
WHERE status = ?
AND batch_code IN($ins)";
try{
$result1=$this->dbh->prepare($query1);
$params[] = $parameter['status'];
foreach ( $parameter['batchcode'] as $p ) {
$params[] = $p;
}
$result1->execute($params);
$data11=$result1->fetchAll(\PDO::FETCH_ASSOC);
return $data11;
}
catch(\PDOException $e) {
print_r($e);
return false;
}
}
hi i have a webapplication with html,css and javascript. I use Bootstrap and jQuery. I have a client and a server site.
On my Client site I have a index.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<button type="button" id="add">Mitarbeiter hinzufügen</button>
<div id="TableContent"></div>
</body>
</html>
here my js:
$(document).ready(function() {
// Fill table with data from server on first load
$.ajax({
type: "GET",
url: "../server/server.php",
data: {
method: "all"
},
success: function(content) {
// Create table content from server data
var table = $.makeTable($.parseJSON(content));
// Append table data to table element in index.html
$(table).appendTo("#TableContent");
}
});
my php:
<?php
// partly from
// gonzalo123.wordpress.com/2010/01/09/building-a-simple-http-client-with-php-a-rest-client
class Request
{
public $url_elements;
public $methode;
public $parameters;
public function __construct()
{
$this->methode = $_SERVER['REQUEST_METHOD'];
$this->url_elements = explode('/', $_SERVER['PATH_INFO']);
// get GET/DELETE or POST/PUT parameters
$parameters = array();
if (isset($_SERVER['QUERY_STRING'])) { // get GET/DELETE parameters
parse_str($_SERVER['QUERY_STRING'], $parameters);
}
$body = file_get_contents("php://input"); // get POST/PUT request body
parse_str($body, $postvars);
foreach ($postvars as $field => $value) {
$parameters[$field] = $value; // overwrite GET/DELETE parameteres
}
$this->parameters = $parameters;
}
}
class RequestHandler
{
public function getAction($request)
{
$data = $request->parameters;
// It's only an example code of how to return data from server
// You need to read information about users from a file data.json
switch ($request->parameters['method']) {
case 'all':
// Create an object of a standard class and add custom
// variables like Id, Vorname, Nachname and so on
$person1 = new stdClass;
$person1->Id = 1;
$person1->Vorname = "Max";
$person1->Nachname = "Mustermann";
$person1->Geburtstag = "11.11.1980";
$person1->Abteilung = "Personal";
$person2 = new stdClass;
$person2->Id = 2;
$person2->Vorname = "Sabine";
$person2->Nachname = "Musterfrau";
$person2->Geburtstag = "05.12.1989";
$person2->Abteilung = "Finanzen";
// Add person in array
$persons = array();
array_push($persons, $person1);
array_push($persons, $person2);
// Encode array to json string and return to client
return json_encode($persons);
break;
case 'single_user':
break;
default: // do nothing, this is not a supported action
break;
}
return json_encode($data);
}
public function deleteAction($request)
{
$data = $request->parameters;
return json_encode($data);
}
public function postAction($request)
{
$data = $request->parameters;
return json_encode($data);
}
public function putAction($request)
{
$data = $request->parameters;
return json_encode($data);
}
}
$request = new Request();
$handler = new RequestHandler();
// tricky: construct call methode depending on HTTP-request-method, e.g. "postAction"
$action = strtolower($request->methode) . 'Action';
$result = $handler->$action($request);
print_r($result);
Check if PATH_INFO is set as this triggers a PHP notice causing invalid json string response. You can also use error_reporting(E_ALL & ~E_NOTICE); to hide notices. See http://php.net/manual/en/function.error-reporting.php
<?php
// partly from
// gonzalo123.wordpress.com/2010/01/09/building-a-simple-http-client-with-php-a-rest-client
class Request
{
public $url_elements;
public $methode;
public $parameters;
public function __construct()
{
$this->methode = $_SERVER['REQUEST_METHOD'];
if(isset($_SERVER['PATH_INFO'])) $this->url_elements = explode('/', $_SERVER['PATH_INFO']);
else $this->url_elements = array();
// get GET/DELETE or POST/PUT parameters
$parameters = array();
if (isset($_SERVER['QUERY_STRING'])) { // get GET/DELETE parameters
parse_str($_SERVER['QUERY_STRING'], $parameters);
}
$body = file_get_contents("php://input"); // get POST/PUT request body
parse_str($body, $postvars);
foreach ($postvars as $field => $value) {
$parameters[$field] = $value; // overwrite GET/DELETE parameteres
}
$this->parameters = $parameters;
}
}
Your script should look like this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "../server/server.php",// adjust this to be a valid relative URL or an absolute URL
data: {
method: "all"
},
dataType: "json",
success: function(content) {
var table = $.makeTable($.parseJSON(content));
$(table).appendTo("#TableContent");
}
});
});
I had developed a event management system using javascript php and mysql. It works perfectly in plain php but now I need to migrate it into codeigniter and need some advice on how to pass the data from js to php while in codeigniter.
My front end java script function is like this
// event creating
dp.onTimeRangeSelected = function (args) {
var name = prompt("New event name:", "Event");
dp.clearSelection();
if (!name) return;
var e = new DayPilot.Event({
start: args.start,
end: args.end,
id: DayPilot.guid(),
resource: args.resource, //Change to classroom name
text: name //Change to event name
});
dp.events.add(e);
args.text = name;
DayPilot.request(
"backend_create.php",
function(req) { // success
var response = eval("(" + req.responseText + ")");
if (response && response.result) {
dp.message("Created: " + response.message);
}
},
args,
function(req) { // error
dp.message("Saving failed");
}
);
};
The php file handling the create function is like this
<?php
require_once '_db.php';
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource)";
$stmt = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
echo json_encode($response);
?>
Now on migrating to codeignitor I moved to segregated the backend_create.php file into model and controller and it looks like this.
The controller part
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TimecalCon extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("Timecal_model");
}
public function insert()
{
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$this->Timecal_model->InsertDetails($name, $start, $end, $resource);
}
The Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Timecal_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function InsertDetails($name, $start, $end, $resource)
{
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource) ";
$query = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
return json_encode($response);
}
The issue is when I change the javascript in the view page and use it like this
.....
DayPilot.request(
"TimecalCon/insert", .......
The functionality breaks and I am unable to insert events into the db. How should I be passing the data from js to the controller in this condition?
We can send the value from javascript to controller using Ajax. I have some code of mine which may help you.
function deleteEmp(empid){
var base_url = '<?php echo site_url(); ?>';
var r=confirm("Do You Really Want to Delete? ")
if (r==true)
{
objPost= new Object();
objPost.empid = empid;
$.ajax({
url:"employee_registration/deleteEmp?empid="+empid,
type:"POST",
data:objPost,
beforeSend:function(data){
},
error:function(data){
},
success:function(data){
alert(data);
result=JSON.parse(data);
alert(result);
if(result.status == 'success'){
alert('Deleted Successfully ');
window.location.reload();
return false;
}
}
});
}else{
return false;
}
}
As you can see I have pass the empid from my view to controller using ajax which gives me result back in variable. Which in this case is json.
Try this
DayPilot.request("<?php echo base_url().'TimecalCon/insert';?>",...)
You'll have to add "url" in "autoload.php" under config folder, then check if the url being loaded is the right one if not. Try modifying base_url() a bit like adding or removing the "index.php" part in the url.
Hope This helps