PDO query failure - mysql

I have a problem with my PDO class. I just have started learning OOP and I don't really know where I made a mistake
My class code:
<?php
class admin
{
private $host = 'mysql:host=localhost;dbname=db501865';
private $username = 'root';
private $password = 'root';
private $conn;
public function connect() {
try {
$conn = new PDO($this->host, $this->username, $this->password);
} catch ( PDOException $e ) {
die( 'Connection failed: ' . $e->getMessage() );
}
return $conn;
}
public function disconnect( $conn ) {
$conn = '';
}
public function listReal()
{
$this ->connect();
$real = $conn->query('SELECT * FROM `real`');
echo '<ul>';
foreach ($real as $row)
{
echo'<li><img src="'.$row['image'].'"></li>';
}
$real -> closeCursor();
echo'</ul>';
}
}
?>
and after executing following code I have 500 error in my browser.
$db = new admin;
$db -> listReal();
Where I made a mistake?

You have to use $this->var_name for your member variables.
Also there is no need to connect if you are already connected.
class admin
{
private $host = 'mysql:host=127.0.0.1;dbname=test';
private $username = 'root';
private $password = 'local#pass';
private $conn;
public function connect() {
if($this->conn) return;
$this->conn = new PDO($this->host, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function disconnect( $conn ) {
$conn = '';
}
public function listReal()
{
$this ->connect();
$real = $this->conn->query('SELECT * FROM `real`');
echo '<ul>';
foreach ($real as $row)
{
echo'<li><img src="'.$row['user_id'].'"></li>';
}
$real -> closeCursor();
echo'</ul>';
}
}
try{
$db = new admin;
$db -> listReal();
} catch(Exception $e) {
echo 'error: '.$e->getMessage();
}

Related

Getting SQLSTATE[HY093]: Invalid parameter number: no parameters were bound in E:\wamp64\www\social\classes\db.php on line 12 error

I'm making a social network's login page but when I login a get the error above. My db.php is (i use pdo):
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
?>
Called from
$user_id = DB::query('SELECT id
FROM users
WHERE email=:email')[0]['id'];
DB::query('INSERT INTO login_tokens
VALUES(\'\', :token, :user_id)',
array(':token'=>sha1($token), ':user_id'=>$user_id));
Your class has many issues. to fix them:
class DB {
protected static $pdo;
public static function connect() {
static::$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'Dani2034');
static::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function query($query, $params = array()) {
$statement = self::$pdo->prepare($query);
$statement->execute($params);
return $statement;
}
}
DB::connect(); // called only once
$user_id = DB::query('SELECT id FROM users WHERE email=?', array($email))->fetchColumn();
DB::query('INSERT INTO login_tokens VALUES(null, ?, ?)', array(sha1($token), $user_id));

PDO 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I see many have had this same message for a number of different reasons but cannot see any solutions that seem to relate to my specific situation, which on the face of it a very simple one. Yes my password etc is md5 and should be changed but I do not believe that is the issue here.
I would appreciate someone pointing out why the first single line code works and the second does not. There is only one line that meets the criteria in the table in each case.
<?php
// Include database class
include 'DBClass.php';
// Instantiate database.
$db = new DBClass();
//***********************
// This works
//***********************
$em = 'admin#infin8integr8.com';
$sid = 39;
$db->query("select ufname,ulname from users where uemail = :em and sub_id = :sb");
$db->bind(':em', $em);
$db->bind(':sb', $sid);
$row = $db->single();
echo $row['ufname'].' '.$row['ulname'].'<br>';
//***************************
// This returns the error 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in C:\wamp\www\pdo\DBClass.php on line 85
//*****************************
//Line 85 in DBClass is "return $this->stmt->execute();" in
//public function execute(){
//return $this->stmt->execute();
//}
$userid = 'f534983b255eb2820bf3ba1438ddcf65';
$password = '0bfd2660362f242169d11e33f7affe0a';
$db->query = ("select ufname,ulname from users where username = :vuid and upwd = :vpwd");
$db->bind(':vuid', $userid);
$db->bind(':vpwd', $password);
$row = $db->single();
echo $row['ufname'].' * '.$row['ulname'].'<br>';
?>
The relevant class code is:-
<?php
class DBClass{
private $host = 'localhost';
private $user = '<user>';
private $pass = '<password>';
private $dbname = 'infinint_infin8';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($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;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
}
?>

how to group the functions in class

i am new to PHP how to group functions inside a class and use it in other pages to reduce typing this is for single page what if i use multiple pages with pageination
this is my coding
<?php
include ('conn.php');
class sel
{
function sell()
{
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and
password ="'.$password.'"');
$x = $rdata['id'];
echo $x;
$_SESSION['username'] =$id;
echo $_SESSION['username'];
if(! $rdata)
{
echo "Enter your username and password correctly";
}
else
{
echo '<script type="text/javascript">
document.location="list.php";
</script>';
}
}
}
}
$myDBObject = new sel();
$myDBObject->sell();
?>
and my connection.php code is
<?php
class DBConnect
{
private $host = 'localhost';
private $user = 'root';
private $pass = '';
private $db = 'enquiry';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
}
$myDBObject = new DBConnect();
$myDBObject->__construct();
$myDBObject->select($select, $table, $where);
?>
if i did like this i get this error what did i do wrong in code
Fatal error: Call to private method DBConnect::select() from context '' in C:\xampp\htdocs
\Raj\cform\conn.php on line 23
You can use database class as mentioned below
class DBConnect
{
private $host = 'localhost';
private $user = 'user';
private $pass = 'pass';
private $db = 'mydb';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
// select query
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
// update query
private function update($update, $table, $where){
// code here
}
}
When required, create object of the class and call functions as below
require 'dbConnect.php'; // assuming, you have included the database class in this file
$myDBObject = new DBConnect();
$username = mysql_real_escape_string($_POST['username']); // mysql escaping
$password = mysql_real_escape_string($_POST['password']); // mysql escaping
// select required data
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and password = "'.$password.'"');
The function described in the class above are for demonstration purpose. You can include other functions in the class along with data escaping functionality.
FYI: mysql is deprecrated. Use mysqli or PDO instead. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
// Hi,
class ClassName {
static function funcName1(){
funcBody1;
}
static function funcName2(){
funcBody2;
}
}
// to use functions juste do :
ClasseName::funcName1();
ClasseName::funcName2();

dynamic fetch data function

i have made simple database application in zend framework.in that i have made user class and defined different function for database interaction.this function are called from controller class..but i have to declare each time class object for calling the method of user class in each action.how can i declare user class object one time and use in all action method of controller.
here is my controller page
class UserController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
Zend_Session::start();
}
public function indexAction()
{
$title = Zend_Registry::get('title');
$this->view->assign('name', 'Wiwit');
$this->view->assign('title', $title);
}
public function logoutAction()
{
Zend_Session::destroy();
$this->redirect("/user/login");
}
public function registerAction()
{
$this->view->assign('title','Register');
$request = $this->getRequest();
$this->view->assign('action', $request->getBaseURL()."/user/register");
if($request->isPost())
{
$data = array('first_name' => $request->getParam('first_name'),
'last_name' => $request->getParam('last_name'),
'user_name' => $request->getParam('user_name'),
'password' => $request->getParam('password')
);
$user = new Application_Model_User();
$rows_affected=$user->user_insert($data);
$this->redirect("/user/login");
}
}
public function loginAction()
{
if(isset($_SESSION['username']))
{
$this->redirect("/user/home");
}
$this->view->assign('title','Register');
$request = $this->getRequest();
$this->view->assign('action', $request->getBaseURL()."/user/login");
if($request->getParam('msg'))
{
$this->view->msg='username or password is invalid';
}
if($request->isPost())
{
$data = array(
'user_name' => $request->getParam('user_name'),
'password' => $request->getParam('password')
);
$user = new Application_Model_User();
$result=$user->user_login($data);
if(empty($result)){
$this->redirect("/user/login/msg/login failed");
}
else{
$_SESSION['username']=$result->user_name;
$this->redirect("/user/home");
}
}
}
public function homeAction()
{
if(isset($_SESSION['username']))
{
$this->view->title='home';
$request = $this->getRequest();
$user = new Application_Model_User();
$result=$user->user_grid();
$this->view->rows=$result;
}
else
{
$this->redirect("/user/login");
}
}
public function editAction()
{
$request = $this->getRequest();
$id= $request->getParam("id");
$user = new Application_Model_User();
$result=$user->user_edit($id);
$this->view->assign('data',$result);
$this->view->action= $request->getBaseURL()."/user/update";
}
}
and here is my user class
<?php
class Application_Model_User extends Zend_Db_Table
{
public function user_insert($data)
{
global $DB;
$rows_affected = $DB->insert('user', $data);
return $rows_affected;
}
public function user_login($data)
{
$u_name=array_shift($data);
$pass=array_shift($data);
$select = $this->_db->select()
->from('user')
->where("user_name = ?",$u_name)
->where("password = ?",$pass);
$result = $this->getAdapter()->fetchRow($select);
return $result;
}
public function user_grid()
{
global $DB;
$sql = 'SELECT * FROM user';
$stmt = $DB->query($sql);
$result = $stmt->fetchall();
return $result;
}
public function user_edit($data)
{
$select = $this->_db->select()
->from('user')
->where("id = ?",$data);
$result = $this->getAdapter()->fetchRow($select);
$data = (array) $result;
return $data;
}
public function userupdate($data,$id)
{
global $DB;
$rows_affected =$DB->update('user', $data,'id = '.$id);
return $rows_affected;
}
public function userdelete($id)
{
global $DB;
$rows_affected =$DB->delete('user','id = '.$id);
return $rows_affected;
}
}
?>
You can create your user object in the init() method, and store it as a class variable.
public function init()
{
/* Initialize action controller here */
Zend_Session::start();
$this->user = new Application_Model_User();
}
Then it's available in any action method.
public function homeAction()
{
if(isset($_SESSION['username']))
{
$this->view->title='home';
$request = $this->getRequest();
$result = $this->user->user_grid(); // changed
$this->view->rows=$result;
}
else
{
$this->redirect("/user/login");
}
}

Fatal error: Call to a member function getPermissionKeyByHandle() on a non-object

Hello I get the following messages at my site www.csvc.nl
Fatal error: Call to a member function getPermissionKeyByHandle() on a non-object in /var/www/vhosts/csvc.nl/httpdocs/cms/updates/concrete5.6.0/concrete/core/models/permission/response.php on line 53
The PHP code is:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class Concrete5_Model_PermissionResponse {
protected $object;
protected $allowedPermissions = array();
protected $customClassObjects = array();
protected $category;
static $cache = array();
public function setPermissionObject($object) {
$this->object = $object;
}
public function getPermissionObject() {
return $this->object;
}
public function setPermissionCategoryObject($category) {
$this->category = $category;
}
public function testForErrors() { }
public static function getResponse($object) {
$r = PermissionCache::getResponse($object);
if (is_object($r)) {
return $r;
}
$category = PermissionKeyCategory::getByHandle(Loader::helper('text')- >uncamelcase(get_class($object)));
if (!is_object($category) && $object instanceof Page) {
$category = PermissionKeyCategory::getByHandle('page');
}
$txt = Loader::helper('text');
$c1 = get_class($object) . 'PermissionResponse';
if (!class_exists($c1)) {
$c1 = 'PagePermissionResponse';
}
$pr = new $c1();
$pr->setPermissionObject($object);
$pr->setPermissionCategoryObject($category);
PermissionCache::addResponse($object, $pr);
return $pr;
}
public function validate($permission, $args = array()) {
$u = new User();
if ($u->isSuperUser()) {
return true;
}
$pk = $this->category->getPermissionKeyByHandle($permission);
if (!$pk) {
print t('Unable to get permission key for %s', $permission);
exit;
}
$pk->setPermissionObject($this->object);
return call_user_func_array(array($pk, 'validate'), $args);
}
public function __call($f, $a) {
$permission = substr($f, 3);
$permission = Loader::helper('text')->uncamelcase($permission);
return $this->validate($permission, $a);
}
}
Does anybody knows what the problem is?
I had a similar issue on an incomplete 5.6.0 upgrade.
Concrete 5 has a core upgrade troubleshooting guide
For me, I just had to do this on my site: http://example.com/index.php/tools/required/upgrade and use the upgrade button.
FYI, this added entries to PermissionKeyCategories and other tables (which existed, but were empty).