PDO "Invalid parameter number: parameter was not defined" yet it is - php

Basically what I'm doing is a users class, which executes a MySQL query in the constructor to retrieve all the users data and store it, like so:
public function __construct($data, $type = 'id')
{
$this->details = Beam::$db->row("SELECT * FROM users WHERE $type = :param", ['param' => $data]);
if(!empty($this->details)) $this->exists = true;
}
This is row() method:
public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)
{
$this->init($query, $params);
return $this->statementQuery->fetch($fetchmode);
}
And init(), where the parameters are bound and the query is executed:
public function init($query, $parameters = '')
{
try {
$this->statementQuery = $this->pdo->prepare($query);
if(!empty($parameters))
{
foreach($parameters as $key => $value)
{
$this->bind($key, $value);
}
}
if(!empty($this->parameters))
{
foreach($this->parameters as $key => &$value)
{
$this->statementQuery->bindParam($key, $value);
}
}
$this->success = $this->statementQuery->execute();
}
catch(PDOException $e)
{
throw new SystemException($e->getMessage() . ' in query: ' . $query, (int) $e->getCode());
}
$this->parameters = array();
}
It should work, I've tested everything multiple times, and debugged using dies() everywhere, but it seems as if I instantiate the class more than one time, the error occurs. It's called multiple times in all my code. Is there something I'm missing?
The error:
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in query: SELECT * FROM users WHERE id = :param
I've also tried debugging printing all the parameters set in PDO by ::debugDumpParams(), and all the parameters are okay, I even var_dump the $this->statementQuery->fetch($fetchmode) from the row() method and it returns everything as it should be...
PS: I bind the array ['param' => $data] afterwards, using this method:
public function bind($param, $value)
{
$this->parameters[':' . $param] = $value;
}
Some examples of where I call the class from:
Login method. Called when the user does login. It fails.
public static function login($user, $password)
{
$user = new User($user, Beam::$con->auth['type']);
if($user->exists == true)
{
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = $user->details["id"];
$username = $user->details["username"];
$user_mail = $user->details["mail"];
$user_password = $user->details["password"];
if(self::verify($password, $user_password))
{
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$_SESSION['user_mail'] = $user_mail;
$_SESSION['user_checksum'] = hash('sha512', $user_password . $user_ip . $user_browser);
Beam::$db->bind("l", time());
Beam::$db->bind("u", $user_id);
Beam::$db->query("UPDATE user_info SET login_timestamp = :l WHERE user_id = :u");
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
This one checks if the user is logged in. It's called almost in every file for authenticated users only.
public static function status()
{
if(isset($_SESSION["user_id"], $_SESSION["username"], $_SESSION["user_checksum"]))
{
$user = new User($_SESSION["user_id"], "id");
if($user->exists)
{
$user_id = $_SESSION['user_id'];
$user_checksum = $_SESSION['user_checksum'];
$username = $_SESSION['username'];
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_password = $user->details["password"];
switch($user_checksum)
{
default:
$checksum_verify = hash('sha512', $user_password . $user_ip . $user_browser);
break;
case "facebook":
$checksum_verify = "facebook";
break;
}
if($checksum_verify == $user_checksum)
{
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}

You need to use the same name for the parameter that you used in the query. In this case you used ":param" so that's what you need to use when you pass in the array of parameters.
change
['param' => $data]
to
[':param' => $data]
and it should work.

Related

try and catch executed at the same time

So i have this OOP Login & register system which gives a user the ability to change his/her name.
When a user is pressing "Update" button his/her name is changed in the DB the problem is that tho it changes the name in DB instead of redirecting the user where i want him/her to be redirected i get the error that should appear only when that name couldn't be changed.
User.php
<?php
class User{
private $_db,
$_data,
$_sessionName,
$_cookieName,
$_isLoggedIn;
public function __construct($user = null){
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
if(!$user){
if(Session::exists($this->_sessionName)){
$user = Session::get($this->_sessionName);
if($this->find($user)){
$this->_isLoggedIn = true;
} else{
//process logout
}
}
} else{
$this->find($user);
}
}
public function update($fields = array(), $id = null){
if(!$id && $this->isLoggedIn()){
$id = $this->data()->id;
}
if(!$this->_db->update('users', $id, $fields)){
throw new Exception('There was a problem updating your profile.');
}
}
public function create($fields = array()){
if(!$this->_db->insert('users', $fields)){
throw new Exception('There was a problem creating an account');
}
}
public function find($user = null){
if($user){
$field = (is_numeric($user)) ? 'id' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if($data->count()){
$this->_data = $data->first();
return true;
}
}
return false;
}
public function login($username = null, $password = null, $remember = false){
if(!$username && !$password && $this->exists()){
Session::put($this->_sessionName, $this->data()->id);
} else{
$user = $this->find($username);
if($user){
if($this->data()->password === Hash::make($password, $this->data()->salt)){
Session::put($this->_sessionName, $this->data()->id);
if($remember){
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if(!$hashCheck->count()){
$this->_db->insert('users_session',array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else{
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
}
}
}
return false;
}
public function exists(){
return(!empty($this->_data)) ? true : false;
}
public function logout(){
$this->_db->delete('users_session', array('user_id', '=', $this->data()->id));
Session::delete($this->_sessionName);
Cookie::delete(Config::get('remember/cookie_name'));
}
public function data(){
return $this->_data;
}
public function isLoggedIn(){
return $this->_isLoggedIn;
}
}
edit-profile.php
<?php
$user = new User();
if(!$user->isLoggedIn()){
Redirect::to('login');
}
if(Input::exists()){
if(Token::check(Input::get('token'))){
$validate = new Validate();
$validation = $validate->check($_POST, array(
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
)
));
if($validation->passed()){
try{
$user->update(array(
'name' => Input::get('name')
));
Session::flash('flash', 'Your profile has been edited with success!');
Redirect::to('flash');
} catch(Exception $e){
die($e->getMessage());
}
} else{
foreach($validation->errors() as $error){
echo $error . '<br />';
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<input type="text" name="name" value="<?php echo escape($user->data()->name); ?>">
</div>
<input type="submit" value="Update">
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
</form>
I have no clue why that is happening
This is the update() method in my DB.class
public function update($table, $id, $fields){
$set = '';
$x = 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if($this->query($sql, $fields)->error()){
return true;
}
return false;
}
For your update function
public function update($table, $id, $fields){
$set = '';
$x = 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if($this->query($sql, $fields)->error()){
return true;
}
return false;
}
Instead do
public function update($table, $id, $fields){
$set = [];
foreach ($fields as $name => $value) {
$set[] = "{$name} = ?";
}
$set = implode(', ', $set);
$sql = "UPDATE {$table} SET {$set} WHERE id = ?";
$fields[] = $id; //id should always be the last ?
if($this->query($sql, $fields)->error()){
return true;
}
return false;
}
Also there is the potential for the table and id and even the keys of $fields to be used as a vector for SQL injection. You may be entering it where ever you use them. But it's possible because you are not checking the table against a white list and anytime you concatenate values into SQL there is the potential for them to be exploited. All it takes is one mistake, you class should not allow coding errors in other places to compromise it's security.
You can get a list of tables from the database itself.
$statement = 'SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` LIKE "'.$database.'"';
So when you connect to the DB you could set a list of acceptable tables then check when a table is put in ( with in_array or such ). Just a thought.
It may also be possible to comprise the keys of the $fields array, for that you can do something similar to the table. but with this query
SHOW COLUMNS FROM {table}
For example, imagine a post request that has inputs matching your array $fields. All someone would have to do is send your server a request with the SQL Attack part in the key instead of the value and you are unprotected. Something like this ( don't drop your DB without a backup, feel i should say that.)
$_POST['1=1; DROP DATABASE --'] = true;
When you construct your query you would have
INSERT INTO table SET 1=1; DROP DATABASE -- = ?, {field} = ? .. rest of query
The -- starts a comment in SQL so nothing after the -- matter to the DB this prevents an error from happening.. So be careful of just dumping post keys into your SQL I'm not sure 1=1 would work but they could use a field out of the input list just as easily. this is just for example purposes.
To me this line
if($this->query($sql, $fields)->error()){
return true;
}else{
return false;
}
Says if there is an error return true not sure if that is the case as i don't know what $this->query or ->error() is but I imagine $this->query must return $this or some object that would contain the error. It's just confusing worded that way.

Fixing max_user_connections in PHP class using PDO

I have been adapting an older abstraction layer to use PDO but I am running into user x has more than 'max_user_connections' active connections SQLSTATE[HY000] [1203] errors when looping through large sets. I have been reading on http://php.net/manual/en/pdo.connections.php but all of my attempts to unset the $dbh from within the loops result in errors from having ended the connection.
Base class looks like
class DB {
public $pdo;
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
public function __construct()
{
$this->connect();
}
private function connect()
{
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8;", $this->user, $this->pass, $options);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
public function __destruct()
{
$this->connection = null;
$this->pdo = null;
unset($this->pdo);
}
// CRUD methods follow including
function retrieve($where, $groupBy='', $order_by='') {
$query = "SELECT * FROM `$this->table` $where $groupBy $order_by";
$q = $this->pdo->prepare($query);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,get_class($this));
// was $result = $q->fetchAll(PDO::FETCH_CLASS,get_class($this));
$this->query_log($query);
$q = null;
if ($result == 'NULL') {
return false;
} else {
return $result;
}
} // retrieve()
And an example that has the errors would be
if (in_array($_GET['type'], $types)) {
$type = $_GET['type'];
$rsObj = new ReservedSlug;
if ($type == 'artist') {
$obj = new CalendarArtist;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'event') {
$obj = new CalendarEvent;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'location') {
$obj = new Location;
$slugfield = 'UrlSlug';
$namefield = 'LocationName1';
}
$needslug = $obj->retrieve("TRIM(`$namefield`) != '' AND (`$slugfield` = '' OR `$slugfield` IS NULL) LIMIT 0,400");
if ($needslug) {
foreach ($needslug as $ns) {
$testslug = slugify($ns->$namefield);
list($reserved) = $rsObj->retrieve("`slug` = '$testslug' AND `type` = '$type'");
if (!$reserved) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug'");
if ($test) {
for ($i = 2; $i < 26; $i++) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug-$i'");
if (!$test) {
$slug = $testslug . '-' . $i;
}
}
} else { // not found in table
$slug = $testslug;
}
} else { // was reserved
$slug = false;
}
echo $ns->$namefield . " gets $slug<p>";
} // foreach needslug
} // if needslug
} // type found in array
So I need to understand how to not create new connections when an active connection is available and how to properly __destruct() these child objects. Where am I going wrong?

Call to undefined function query() when it is defined

I have searched through similar questions and can't find the answer, though I am a beginner so may have missed it.
I am trying to call the review_create() function I have included the reviews.php which contains this function. However, I am getting the error
Fatal error: Call to undefined function query() in C:\xampp\htdocs\cafe\review.php
The PHP for user_pages.php:
<?php
require_once 'review.php';
require_once 'cafe.php';
require_once 'logged_in.php';
$RATING_MAP = array('5' => 'Excellent', '4' => 'Good', '3' => 'Ok', '2' => 'Bad', '1' => 'Awful', '0' => '---');
$error = array();//holds multiple errors
$id = $rating = $review = $action = '';
$self = $_SERVER['PHP_SELF'];
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
}
if ($action == 'delete') {
if (isset($_REQUEST['id'])) {
review_delete($_REQUEST['id'], $error);
} else {
$error[count($error)] = "Cannot delete the review, missing ID!";
}
}
elseif ($action == 'create') {
if ((isset($_REQUEST['rating']))
&& (isset($_REQUEST['review'])
&& (isset($_REQUEST['review_cafe'])))) {
$rating = $_REQUEST['rating'];
$review = $_REQUEST['review'];
$review_cafe = $_REQUEST['review_cafe'];
if ($rating == '---' or $review == '' or $review_cafe == '') {
$error[count($error)] = "You must provide a cafe, rating and review!";
} else {
review_create($review_cafe, $rating, $review, $error);
}
}
else {
$error[count($error)] = "Unable to create review, missing parameters!";
}
}
?>
The PHP for reviews.php:
<?php
require_once "sql.php";
function review_create($review_cafe, $rating, $review, &$error) {
$query = "INSERT INTO Reviews (cafe, rating, review) VALUES (". "'$review_cafe', $rating, '$review');";
$success = query($query, $error);
return $success;
}
?>
Here is sql.php where $query is defined:
<?php //sql.php
require_once "sql_constants.php";
class Sql {
private static $connection = false;
private static $error; // holds the last error.
static function getConnection() {
if (!Sql::$connection) {
Sql::setConnection(mysqli_connect(SQLHOST, SQLUSER, SQLPASSWORD, HOSTDB));
if (!Sql::$connection) {
Sql::setConnection(false);
Sql::setError("Could not connect...");
}
}
return Sql::$connection;
}
private static function setConnection($iConnection) {
Sql::$connection = $iConnection;
}
private static function setError($iError) {
Sql::$error = $iError;
}
static function getError() {
return Sql::$error;
}
static function query($query) {
$result = false;
Sql::setError(false); // reset the error
if ($link = Sql::getConnection()) {
$result = mysqli_query($link, $query);
if (!$result)
Sql::setError(mysqli_error($link));
}
return $result;
}
static function getInsertID() {
// Returns the last id automatically inserted into the
// database.
return mysqli_insert_id(Sql::getConnection());
}
}
?>
Cheers
James
Avoid using mysql, use mysqli_ instead and update your code to use mysqli_query in place of query (that is the error!!)
simply do :
return (mysqli_query( $conn, $query )); //$conn is connection object
OR, if you are doubtfull of result, use mysqli_error()
$success = mysqli_query($con, $query);
if ( $success === false)
{
printf("Error is : ", mysqli_error($con));
}
else
{
return ($success);
}
error here- $success = query($query, $error);
It should be - $success = mysql_query($query, $error);
unless You do have a method query() which executes the query
I prefer to use PDO or MYSQLI instead of that, which is easy to inject. (http://en.wikipedia.org/wiki/SQL_injection) see http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

PDO user class wont get post data

I've tried everything I know but it's still not working. I cannot get any posted data from my HTML form and I know it's not getting the data from the HTML form because I've tried to change the values and execute without the form and then it works.
Here is my html form:
<?php
ob_start();
session_start();
error_reporting(E_ALL);
if (!ini_get('display_errors')) { ini_set('display_errors', '1');}
include 'classes/user.class.php';
include 'classes/database.class.php';
include 'classes/config.class.php';
include 'classes/bcrypt.class.php';
if(isset($_POST['submitted'])) {
$user = new MonetizeMedia\Classes\User;
$db = new MonetizeMedia\Classes\Database;
$username = $_POST['username'];
$password = $_POST['password'];
$user->username = $username;
$user->password = $password;
if($user->createUser()) {
echo "DONE!";
}
else
{
echo "<br />An error occured while creating your account. Please try later.";
return;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Register</title>
</head>
<body>
<form method="post" action="">
<ul>
<li>
<label for="usn">Username : </label>
<input type="text" name="username" />
</li>
<li>
<label for="passwd">Password : </label>
<input type="password" name="password" />
</li>
<li class="buttons">
<input type="submit" name="submitted" value="Register" />
</li>
</ul>
</form>
</body>
</html>
my user class
<?php
namespace MonetizeMedia\Classes;
class User {
private $uid;
private $fields;
public function __construct() {
$this->uid = null;
$this->fields = array('username' => '',
'password' => '');
}
public function __get($field) {
if($field == 'uid')
{
return $this->uid;
}
else
{
return $this->fields[$field];
}
}
public function __set($field, $value) {
if(array_key_exists($field, $this->fields))
{
$this->fields[$field] = $value;
}
}
public function validateUsername($username) {
return preg_match('/^[a-zA-Z]{4,15}$/i', $username);
}
public function validateEmailAddr($email) {
return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email);
}
public function getUserById($id) {
$user = new \MonetizeMedia\Classes\User;
$db = new \MonetizeMedia\Classes\Database;
$sql = "SELECT * FROM users WHERE uid = :uid";
$db->prepare($sql);
$db->bindParam(":uid", $id);
$row = $db->fetchAll();
$user->uid = $row['uid'];
$user->username = $row['username'];
$user->password = $row['password'];
return $user;
}
public function getByUsername($username) {
$user = new \MonetizeMedia\Classes\User;
$db = new \MonetizeMedia\Classes\Database;
$sql = "SELECT * FROM users WHERE username = :username";
$db->prepare($sql);
$db->bindParam(":username", $username);
$row = $db->fetchAll();
$user->uid = $row['uid'];
$user->username = $row['username'];
$user->password = $row['password'];
return $username;
}
public function createUser() {
try {
$username = null;
$password = null;
$db = new \MonetizeMedia\Classes\Database();
$bcrypt = new \MonetizeMedia\Classes\Bcrypt(15);
/*** query ***/
$sql = 'INSERT INTO users(username, password) VALUES(:username, :password)';
/*** prepare the select statement ***/
$db->prepare($sql);
/*** bind the parameters ***/
$db->bindParam(":username", $username);
$db->bindParam(":password", $bcrypt->hash($password));
//$db->bindParam(":username", "test");
//$db->bindParam(":password", $bcrypt->hash("test"));
/*** execute the prepared statement ***/
$db->execute();
$result = $db->fetchAll();
return $result;
} catch ( \PDOException $e ) {
return $e->getMessage();
}
}
}
?>
Here is my database class:
<?php
namespace MonetizeMedia\Classes;
use PDO;
class Database {
private $db = array();
private $dbh;
private $error;
private $stmt;
public function __construct() {
$Config = new \MonetizeMedia\Classes\Config;
$this->db['username'] = $Config->DB_USERNAME;
$this->db['password'] = $Config->DB_PASSWORD;
$this->db['database'] = $Config->DB_DATABASE;
$this->db['server'] = $Config->DB_SERVER;
$this->db['port'] = $Config->DB_PORT;
$this->db['encoding'] = $Config->DB_ENCODING;
try {
/* Create a connections with the supplied values */
$this->dbh = new \PDO("mysql:host={$this->db['server']};dbname={$this->db['database']};port={$this->db['port']};charset={$this->db['encoding']}", $this->db['username'], $this->db['password']);
$this->dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); // throw exceptions on errors (default: stay silent)
$this->dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); // important! use actual prepared statements (default: emulate prepared statements)
$this->dbh->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_CLASS); // fetch associative arrays (default: mixed arrays)
$this->dbh->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8" ); // set encoding to utf8
} catch( \PDOException $e ) {
/* If any errors echo the out and kill the script */
echo "<center><b>[DATABASE] Error - Connection Failed:</b> " . $this->error = $e->getMessage() . "<br/><br/><br/></center>";
echo "<center><b>We are currently experiencing technical difficulties. We have a bunch of monkeys working really hard to fix the problem.</b></center>";
die();
}
}
public function prepare($sql) {
try {
$this->stmt = $this->dbh->prepare($sql);
} catch ( \PDOException $e ) {
$e->getMessage();
// throw new InvalidSQLException("Invalid SQL. Statement could not be prepared.");
}
}
public function bindParam($param, $value, $type = null) {
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
break;
}
}
return $this->stmt->bindParam($param, $value, $type);
}
public function execute() {
try {
return $this->stmt->execute();
} catch ( \PDOException $e ) {
$e->getMessage();
}
}
public function fetchAll() {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch() {
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount() {
return $this->stmt->rowCount();
}
public function lastInsertId() {
return $this->dbh->lastInsertId();
}
public function beginTransaction() {
return $this->dbh->beginTransaction();
}
public function endTransaction() {
return $this->dbh->commit();
}
public function cancelTransaction() {
return $this->stmt->rollBack();
}
public function debugDumpParams() {
return $this->stmt->debugDumpParams();
}
public function errorInfo() {
return $this->dbh->errorInfo();
}
public function countAll($arr) {
return count($arr);
}
}
?>
I've been sitting with this problem for more than 10 hours without a proper solution.
What exactly is not working?
Anyways, you should rewrite your createUser method:
$username = null;
$password = null;

pdo page wise fetching

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

Categories