Thanks for your help in advance.
I have just migrated my webserver from apache to nginx. Session information was happily being stored in the database previously, now for some reason they are writing to the /tmp directory.
Here is the code to set the session handler:
session_write_close();
$sess = new sessionHandler();
session_set_save_handler(array($sess, 'open'),
array($sess, 'close'),
array($sess, 'read'),
array($sess, 'write'),
array($sess, 'destroy'),
array($sess, 'gc'));
register_shutdown_function('session_write_close');
session_start();
$cookieLifetime = 365 * 24 * 60 * 60;
setcookie(session_name(),session_id(),time()+$cookieLifetime);
and here is the session handler class:
class appSessionHandler {
private $db;
public function open($save_path, $session_name) {
$this -> db = new appSql();
return true;
}
public function close() {
$this -> db -> close();
}
function read($id) {
// Create Memcache Class
$memcache = new memcacher();
var_dump('123');
// Check Memcache
$memcache->key = 'session-' . $id;
$memcache->get();
// If results is in memcache
if ($memcache->result != false){
$res = $memcache->result;
return $res;
}
// Else get the result from sql and update cache
else{
$this->open();
$this->db->sqlQuery = "SELECT data FROM session WHERE id = :id";
$this->db->params = array('id' => $id);
$res = $this->db->sqlQuery();
if (count($res) >= 1){
$memcache->input = $res[0]->data;
$memcache->duration = 2000;
$memcache->set();
return $res[0]->data;
}
return '';
}
}
function write($id, $data) {
$access = time();
$this->open();
// Create Memcache Class
$memcache = new memcacher();
// Check Memcache
$memcache->key = 'session-' . $id;
$memcache->input = $data;
$memcache->duration = 2000;
$memcache->set();
$this->db->sqlQuery = "REPLACE INTO session VALUES (:id, :access, :data)";
$this->db->params = array('id' => $id, 'access' => $access, 'data' => $data);
return $this->db->sqlQuery();
}
function destroy($id) {
// Delete From SQL
$this->open();
$this->db->sqlQuery = "DELETE FROM session WHERE id = :id";
$this->db->params = array('id' => $id);
// Create Memcache Class
$memcache = new memcacher();
// Check Memcache
$memcache->key = 'session-' . $id;
$memcache->delete();
return $this->db->sqlQuery();
}
function gc($max) {
$old = time() - $max;
$this->open();
$this->db->sqlQuery = "DELETE FROM session WHERE access < :old";
$this->db->params = array('old' => $old);
return $this->db->sqlQuery();
}
public function killUserSession($username){
$this->open();
$this->db->sqlQuery = "delete from session where data like('%userID|s:%\" :username %\";first_name|s:%')";
$this->db->params = array('username' => $username);
$this->db->sqlQuery();
}
}
I am lost!
Related
When I want to update my articles table from MySQL database I get the following error
PDOStatement::execute() expects parameter 1 to be array, bool given in /Users/Iceson/Sites/blog jean/app/Database.php on line 49
Here the update code from my managementpost.php
if(isset($_POST['update'])) {
$id = $_POST['id'];
$titre = $_POST['titre'];
$contenu = $_POST['contenu'];
App\App::getDb()->prepare("UPDATE articles SET titre ='$titre',
contenu ='$contenu' WHERE id='id'",true);
}
Here is the my database class from my database.php, the error is located on the line $req->execute($attributes); in the function prepare
<?php
namespace App;
use \PDO;
class Database {
private $db_name;
private $db_user;
private $db_pass;
private $db_host;
private $pdo;
public function __construct($db_name, $db_user = 'root', $db_pass = 'root', $db_host = 'localhost') {
$this->db_name = $db_name;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->db_host = $db_host;
}
private function getPDO() {
if ($this->pdo === null) {
$pdo = new PDO('mysql:host=localhost;dbname=blogdejean;charset=utf8', 'root', 'root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo = $pdo;
}
return $this->pdo;
}
public function query($statement, $class_name = null, $one = false) {
$req = $this->getPDO()->query($statement);
if($class_name === null) {
$req->setFetchMode(PDO::FETCH_OBJ);
} else {
$req->setFetchMode(PDO::FETCH_CLASS, $class_name);
}
if($one) {
$datas = $req->fetch();
} else {
$datas = $req->fetchALL();
}
return $datas;
}
public function prepare($statement, $attributes, $class_name = null, $one = false) {
$req = $this->getPDO()->prepare($statement);
$req->execute($attributes);
if($class_name === null) {
$req->setFetchMode(PDO::FETCH_OBJ);
} else {
$req->setFetchMode(PDO::FETCH_CLASS, $class_name);
}
if($one) {
$datas = $req->fetch();
} else {
$datas = $req->fetchALL();
}
return $datas;
}
}
You are using your database class wrong: Instead of sending a statement with parameters you can bind, you inject the values in the sql statement making your query vulnerable to sql injection.
And where you need to send an array of values to bind, you send a boolean.
So you need to replace this:
App\App::getDb()->prepare("UPDATE articles SET titre ='$titre', contenu ='$contenu' WHERE id='id'",true);
with:
App\App::getDb()->prepare(
"UPDATE articles SET titre = ?, contenu = ? WHERE id = ?",
[
$_POST['titre'],
$_POST['contenu'],
$_POST['id'],
]
);
You should probably also re-think why you are extending PDO like that; fetching all rows does not make sense on an update statement for example.
thanks y'all now i have a general error "General error in /Users/Iceson/Sites/blog jean/app/Database.php:58" it's the $datas = $req->fetchALL(); i think i messed up my database class everything was working until the update part, i don't know what's wrong
public function prepare($statement, $attributes, $class_name = null, $one = false) {
$req = $this->getPDO()->prepare($statement);
$req->execute($attributes);
if($class_name === null) {
$req->setFetchMode(PDO::FETCH_OBJ);
} else {
$req->setFetchMode(PDO::FETCH_CLASS, $class_name);
}
if($one) {
$datas = $req->fetch();
} else {
$datas = $req->fetchALL();
}
return $datas;
}
You prepare method expects a array as the second argument ($attributes), but you passed it true.
App\App::getDb()->prepare("UPDATE articles SET titre ='$titre', contenu ='$contenu' WHERE id='id'",true);
It should be something like this.
App\App::getDb()->prepare("UPDATE articles SET titre = :titre, contenu = :contenu WHERE id= :id",[':titre' => $titre, ':contenu' => $contenu, ':id' => $id ]);
I'm currently learning php and trying to write session data to my database without success.
I have a setup with Apache24, PHP 7 environment and Postgresql database.
When I instantiate sessionhandling class ($sess = new sessionhandling) in my other PHP file nothing is written to database. However, when I pass variable to and call the write function ($sess->write), data is written to the database.
(Hope this is not a duplicate of any other questions raised. Done a lot of searches on Stackoverflow and Google, but not found any answers that solve my challenge)
My session handler code is as follows:
<?php
Include(dirname(__DIR__).'\Userstories\db\Connection.php');
class sessionhandling extends Connecting implements SessionHandlerInterface {
public function __construct(){
// Set handler to overide SESSION
session_set_save_handler(
array(&$this, "open"),
array(&$this, "close"),
array(&$this, "read"),
array(&$this, "write"),
array(&$this, "destroy"),
array(&$this, "gc")
);
register_shutdown_function('session_write_close');
// Start the session
session_start();
session_write_close;
}
public function open($save_path, $id) {
if(self::get()->connect()) {
return true;
} else {
return false;
}
}
public function close() {
if(self::get()->connect()->pdo = Null) {
return true;
} else {
return false;
}
}
public function read($id) {
//$pdo = Connecting::get()->connect();
$ipdo = self::get()->connect();
$q_udata = "SELECT data FROM sessions WHERE id=:id";
$stmt=$ipdo->prepare($q_udata);
$stmt->bindvalue(':id', $id);
$stmt->execute();
if($stmt->execute()) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$ipdo = NULL;
return $row['data'];
} else {
$ipdo = NULL;
return '';
}
}
public function write($id, $data){
$id = (string) $id;
$data = (string) $data;
$access = time();
$ipdo = self::get()->connect();
$c_id = "SELECT id FROM sessions WHERE id=:id";
$stmt=$ipdo->prepare($c_id);
$stmt->bindvalue(':id', $id);
$stmt->execute();
$idarray=$stmt->fetch(PDO::FETCH_ASSOC);
$row_id = $idarray['id'];
if(empty($row_id)) {
$sessionids = 'INSERT INTO sessions(id, data, access) VALUES(:id, :data, :access)';
$stmt = $ipdo->prepare($sessionids);
$stmt->bindvalue(':id', $id);
$stmt->bindvalue(':access', $access);
$stmt->bindvalue(':data', $data);
$stmt->execute();
session_write_close();
} else {
$rep_data = "UPDATE sessions SET data = :data, access = :access WHERE id = :id";
$stmt=$ipdo->prepare($rep_data);
$stmt->bindvalue(':id', $id);
$stmt->bindvalue(':access', $access);
$stmt->bindvalue(':data', $data);
$stmt->execute();
session_write_close();
}
if($stmt->execute()) {
$ipdo = NULL;
return true;
} else {
$ipdo = NULL;
return false;
}
}
public function destroy($id) {
$ipdo = self::get()->connect();
$del_data = "DELETE FROM sessions WHERE id =:id";
$stmt = $ipdo->prepare($del_data);
$stmt->bindvalue(':id', $id);
$stmt->execute();
if($stmt->execute()) {
$ipdo = NULL;
return true;
} else {
$ipdo = NULL;
return false;
}
}
public function gc($max) {
$old = time() - $max;
$ipdo = self::get()->connect();
$cleanup = "DELETE * FROM sessions WHERE access < :old";
$stmt = $ipdo->prepare($cleanup);
$stmt->bindvalue(':old', $old);
$stmt->execute();
if($stmt->execute()) {
$ipdo = NULL;
return true;
} else {
$ipdo = NULL;
return false;
}
}
}
?>
When I remove the 'implements SessionHandlerInterface' sessionhandling class and remove the parameters $save_path, $id from open function, I get the following error: "Warning: session_start(): Failed to read session data: user (path: ) in C:\Users\Public\Server\Apache24\htdocs\Userstories\sessionhandling.php on line 19"
Is it reuiqred to define the $save_path when using DB for session handling? If so, what should the $save_path be?
Any advise on how to get my session handler to write to DB is very much appreciated.
I made ut work by changing my read function to this and ensuring that a string is returned:
public function read($id) {
//$pdo = Connecting::get()->connect();
$ipdo = self::get()->connect();
$q_udata = "SELECT data FROM sessions WHERE id=:id";
$stmt=$ipdo->prepare($q_udata);
$stmt->bindvalue(':id', $id);
$stmt->execute();
if($stmt->execute()) {
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
$ipdo = NULL;
$data = $row['data'];
return (string) $data;
} else {
$ipdo = NULL;
return '';
}
}
I know this has been pointed out in other posts, but I thought that my $data = $row['data'] would return a string in the first place.
I need help with the class below - its not writing to the database and I have no idea why. I know the "read" method is called, but not the "write" method :S
This is the code I'm using:
require '../application/database.php';
$db = new Database('localhost', 'root', '', 'gemgale');
require '../application/session.php';
$session = new Session($db);
session_set_save_handler(
array(&$session, 'open'),
array(&$session, 'close'),
array(&$session, 'read'),
array(&$session, 'write'),
array(&$session, 'destroy'),
array(&$session, 'clean')
);
session_start();
var_dump($session);
$_SESSION['something'] = "gem";
var_dump($_SESSION);
#$session->delete();
#var_dump($_SESSION);
and this is the class ...
class Session
{
###########################################################################
private $expiry = 3600;
private $securityCode = "gnvriev847e8grdinvrdg5e8g4r7fr7rdvreh8^£*^£FGgyhf";
private $tableName = "session_data";
###########################################################################
private $dbh;
function __construct(Database $db)
{
$this->dbh = $db->getConnection();
ini_set('session.cookie_lifetime', 0);
ini_set('session.gc_maxlifetime', $this->expiry);
}
function open($save_path, $session_name)
{
return true;
}
function close()
{
return true;
}
function read($session_id)
{
echo $session_id;
print "READING";
$time = time();
$hua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$hua = $hua . $this->securityCode;
$hua = md5($hua);
try {
$stmt = $this->dbh->prepare("
SELECT session_data
FROM :tableName
WHERE session_id = :sesID
AND session_expire > :time
AND http_user_agent = :hua
LIMIT 1
");
$stmt->bindParam("tableName", $this->tableName);
$stmt->bindParam("sesID", $session_id);
$stmt->bindParam("time", $time);
$stmt->bindParam("hua", $hua);
$stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
$rs = $stmt->fetch();
if (!$rs)
return '';
else
return $rs['session_data'];
}
function write($session_id, $session_data)
{
print "WRITING";
$expiry = time() + $this->expiry;
$hua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$hua = $hua . $this->securityCode;
$hua = md5($hua);
try {
$stmt = $this->dbh->prepare("
INSERT INTO :tableName (
session_id,
http_user_agent,
session_data,
session_expiry
)
VALUES (
:sessID,
:hua,
:sdata,
:expiry
)
ON DUPLICATE KEY UPDATE
session_data = :sdata,
session_expire = :expiry
");
$stmt->bindParam("tableName", $this->tableName);
$stmt->bindParam("sessID", $session_id, PDO::PARAM_STR);
$stmt->bindParam("hua", $hua);
$stmt->bindParam("sdata", $session_data, PDO::PARAM_STR);
$stmt->bindParam("expiry", $expiry);
$stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
if ($stmt->rowCount() > 1)
return true;
else
return '';
}
function destroy($session_id)
{
try {
$stmt = $this->dbh->prepare("
DELETE FROM :tableName
WHERE session_id = :id
");
$stmt->bindParam("tableName", $this->tableName, PDO::PARAM_STR);
$stmt->bindParam("id", $session_id, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
return true;
}
function clean($maxLifeTime)
{
try {
$x = time() - $maxLifeTime;
$stmt = $this->dbh->prepare("
DELETE FROM :tableName
WHERE session_expire < :x
");
$stmt->bindParam("tableName", $this->tableName, PDO::PARAM_STR);
$stmt->bindParam("x", $x, PDO::PARAM_INT);
$stmt->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
return true;
}
function delete()
{
$oldID = session_id();
session_regenerate_id();
$this->destroy($oldID);
session_unset();
session_destroy();
}
function getActive()
{
$this->clean($this->expiry);
try {
$stmt = $this->dbh->prepare("
SELECT COUNT(session_id) as count
FROM :tableName
");
$stmt->bindParam("tableName", $this->tableName, PDO::PARAM_STR);
$stmt->execute();
$rs = $stmt->fetch();
return $rs['count'];
} catch (PDOException $e) {
die($e->getMessage());
}
}
}
Hope you guys can help :)
Thanks,
Gem
One, you don't need to pass by reference. Do this instead:
session_set_save_handler(
array($session, 'open'),
array($session, 'close'),
array($session, 'read'),
array($session, 'write'),
array($session, 'destroy'),
array($session, 'clean')
);
To test if the save/write is working, you could try this:
session_start();
$_SESSION['something'] = "gem";
session_write_close();
echo "- Foo";
This should trigger a write to the session store and flush anything to be written. In this case it should display WRITING- Foo if your write method is being called.
If the DB is not being written, but the method is being called, there are other issues.
The first thing I'd look at is the :tableName you're replacing in the prepared statement. You cannot prepare-replace column names or tables. Change your statement to this:
$stmt = $this->dbh->prepare("
INSERT INTO ".$this->tableName." (
session_id,
http_user_agent,
session_data,
session_expiry
)
VALUES (
:sessID,
:hua,
:sdata,
:expiry
)
ON DUPLICATE KEY UPDATE
session_data = :sdata,
session_expire = :expiry
");
If you do substitue in variables for table names or columns, make sure you whitelist them before using to be safe against opening an injection hole.
We've just updated PHP on our server, for the most part everything is fine, but the mssql_ functions aren't supported any more unfortunately. I've tried to update our previous class:
$connection['server'] = 'server, port';
$connection['user'] = 'user';
$connection['pass'] = 'pass';
$connection['db'] = 'db';
class mssqlClass {
function connect($dbhost = NULL){
global $connection;
if(! ISSET ($dbconnect)){
$dbconnect = mssql_Connect($connection['server'], $connection['user'], $connection['pass'], true);
}
if(! $dbconnect){
return 'Failed to Connect to Host';
}else{
$select = mssql_select_db($connection['db'], $dbconnect);
if(! $select){
return 'Failed to select Database';
}else{
return $dbconnect;
}
}
}
function getData ($query){
$this->data_array = array();
$result = mssql_query($query);
while ($row = mssql_fetch_assoc($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query){
$result = mssql_query($query) or die("Query didn't work");
}
}
To be compliant with sqlsrv_, and whilst I can connect to the database without any issues, it won't return any data!:
class mssqlClass {
function connect($database = 'Db') {
$mssql_server = 'server';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
if(! ISSET ($dbconnect)){
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
}
if(! $dbconnect){
return 'Failed to connect to host';
}
}
function getData ($query) {
$result = sqlsrv_query($db->connect, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
}
ps. Example usage is as follows:
$db = new mssqlClass();
$conn = $db->connect('DATABASE');
$query = "SELECT * FROM Table";
$result= $db->getData($query);
So sorry for the horrible amount of code - I can edit it down to just the getData function if that's easier? Thank you!!
I've made some changes in your class:
<?php
class mssqlClass {
protected $connection = null;
public function connect($database = 'Db') {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($this->connection, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work..");
}
}
The code looks fine. The only thing which could be your problem is that sqlsrv_fetch_array needs maybe a second parameter e.g.:
sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Because the default is that it returns two arrays with different formats. And if you may acess attributes by name it will return nothing but not fail.
Something like this. Because you actually call the sqlsrv_query method with the return value of the following method. And in the original version you missed to return the connection resource.
function connect($database = 'Db') {
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
return $dbconnect;
}
in advance
function getData ($query) {
$result = sqlsrv_query($db->connect(), $query);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
I found this page while trying to find a quick short-cut to someone else's wrapper class for sqlsrv commands. Since this wasn't really complete, I have compiled my own quickly. Please don't think this is production code, you should test and test again, but it might help someone out of a jam quickly.
class db {
protected $connection = null;
private $debug = true;
private $stmt = null;
private $insertid = null;
private $affectedrows = null;
public function db($host = '.',$database,$username,$password) {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
// data for making connection
$sqlsvr_details = array( 'UID' => $username,
'PWD' => $password,
'Database' => $database,
'CharacterSet' => 'UTF-8'
);
// try to connect
$this->connection = sqlsrv_connect($host, $sqlsvr_details);
if($this->connection == false){
$this->debug('Failed to connect to host: '.$this->errors(),true);
return false;
}else{
return true;
}
}
public function query($query) {
return new resultset($query,$this->connection,$this->debug);
}
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
public function delete($query){
return $this->update($query);
}
public function update($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
$this->affectedrows = #sqlsrv_rows_affected($this->stmt);
return $this;
}
}
public function insert($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
//Get the last insert ID and store it on here
$this->insertid = $this->query('select ##IDENTITY as insert_id')->asObject()->insert_id;
return $this;
}
}
public function insert_id(){
return $this->insertid;
}
public function affected_rows(){
return $this->affectedrows;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}
class resultset implements Countable,Iterator {
private $result = null;
private $connection = null;
private $debug = false;
private $internal_pointer = 0;
private $data = array();
public function resultset($query,$link,$debug = false){
$this->connection = $link;
$this->debug = $debug;
$this->result = sqlsrv_query($this->connection, $query, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
if ($this->result == false){
$this->debug('Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
return $this;
}
}
public function asObject($step = true){
$object = sqlsrv_fetch_object($this->result,NULL,NULL,SQLSRV_SCROLL_ABSOLUTE,$this->internal_pointer);
if (! $object){
return false;
}else{
if ($step) $this->internal_pointer++;
return $object;
}
}
public function num_rows() {
return sqlsrv_num_rows($this->result);
}
public function free(){
$this->internal_pointer = 0;
if (is_resource($this->result)){
sqlsrv_free_stmt($this->result);
}
}
public function __destory(){
$this->free();
}
//Countable Function
public function count(){
return $this->num_rows();
}
//Iteration Functions
public function rewind(){
$this->internal_pointer = 0;
}
public function current(){
return $this->asObject(false);
}
public function key(){
return $this->internal_pointer;
}
public function next(){
$this->internal_pointer++;
}
public function valid(){
return $this->internal_pointer <= $this->num_rows();
}
//============================================
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}
I am using this php pdo wrapper.This is my database class .
class Db
{
private static $_pdoObject = null;
protected static $_fetchMode = PDO::FETCH_ASSOC;
protected static $_connectionStr = null;
protected static $_driverOptions = array();
private static $_username = null;
private static $_password = null;
public static function setConnectionInfo($schema, $username = null, $password = null, $database = 'mysql', $hostname = 'localhost')
{
if($database == 'mysql') {
self::$_connectionStr = "mysql:dbname=$schema;host=$hostname";
self::$_username = $username;
self::$_password = $password;
} else if($database == 'sqlite'){
// For sqlite, $schema is the file path
self::$_connectionStr = "sqlite:$schema";
}
// Making the connection blank
// Will connect with provided info on next query execution
self::$_pdoObject = null;
}
public static function getResult($sql, $params = array())
{
$statement = self::_query($sql, $params);
return $statement->fetchAll(self::$_fetchMode);
}
private static function _query($sql, $params = array())
{
if(self::$_pdoObject == null) {
self::_connect();
}
$statement = self::$_pdoObject->prepare($sql, self::$_driverOptions);
$arrayjson1=array(
'success' => false,
'message'=>'database error '
);
$msg= formjson(array(),array(),$arrayjson1);
if (! $statement) {
$errorInfo = self::$_pdoObject->errorInfo();
//~ print_r($errorInfo);
//~ echo $msg;exit;
throw new PDOException("Database error [{$errorInfo[0]}]: {$errorInfo[2]}, driver error code is $errorInfo[1]");
}
$paramsConverted = (is_array($params) ? ($params) : (array ($params )));
if ((! $statement->execute($paramsConverted)) || ($statement->errorCode() != '00000')) {
$errorInfo = $statement->errorInfo();
//~ print_r($errorInfo);
throw new PDOException("Database error [{$errorInfo[0]}]: {$errorInfo[2]}, driver error code is $errorInfo[1]");
//~ echo $msg;exit;
}
return $statement;
}
}
I am calling this query for getting all the users
$sql="select userid,concat_ws(' ',firstname,lastname) as name $fields
from users where 1=1 $condition order by updatedon $limit";
$row=Db::getResult($sql,$query);
I want that by
Input
passing
No. of record per page
2.Page No.
So that it
output
come should be the records of that page only by record per page .
How can i achieve this in pdo.
Please help.Thanks
read the following article. That will help you understand the criteria you are interested in.
paging