unserialize pdo mysql error - invalid data source name - mysql

I have these classes below for my online store.
This super class holds all common methods used by the child classes.
class grandpa
{
public function test1($string)
{
return $string;
}
}
So do the PDO connection,
class database_pdo extends grandpa
{
protected $connection = null;
protected $dsn,$username,$password;
public function __construct($dsn,$username,$password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->get_connection();
}
public function get_connection()
{
try
{
$this->connection = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
$this->get_error($e);
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->get_connection();
}
public function get_error($e)
{
$this->connection = null;
die($e->getMessage());
}
public function __destruct()
{
$this->connection = null;
}
}
I have this class extend from pdo for other common methods that require pdo connection,
class papa extends database_pdo
{
protected $connection = null;
public function __construct($connection)
{
$this->connection = $connection;
}
public function test2($string)
{
return $string;
}
}
The child classes,
class kido_1 extends papa
{
public function __construct($connection)
{
parent::__construct($connection);
}
public function test3($string)
{
return $string;
}
}
How it use the classes above,
# Host used to access DB.
define('DB_HOST', 'localhost');
# Username used to access DB.
define('DB_USER', 'xxx');
# Password for the username.
define('DB_PASS', 'xxx');
# Name of your databse.
define('DB_NAME', 'xxx');
# Data source name.
define('DSN', 'mysql:host='.DB_HOST.';dbname='.DB_NAME);
$connection = new database_pdo(DSN,DB_USER,DB_PASS);
$kido = new kido($connection);
$_SESSION['cart'] = serialize($kido);
$kido = unserialize($_SESSION['cart']);
print_r($kido->test3('hello'));
I get this error,
invalid data source name
It is caused by unserialize() that I need it for my cart data...
How can I fix this? Or a better way of rewrite these classes?

Your papa::connection is a PDO object. Therefore, when you are trying to serialize $kido, you are trying to serialize a resource, which is not possible.
Try adding a $this->connection = null; in your database_pdo::__sleep() method.

a solution I think...
class papa extends grandpa
{
protected $connection = null;
public function __construct($connection)
{
$this->connection = $connection;
}
public function test2($string)
{
return $string;
}
}

Related

Symfony 6 json_login don't authenticate user

I have running a simple symfony/skeleton.
Basically I followed the documentation on "json_login", however Symfony does not authenticate the user when the login route is called. I test via Thunder Client in VSC.
I can call the /login route method, but the user object is basically NULL. In the meantime I have also tried to use my own authenticator, however this has not brought me any further in all variations. I have first tested with Symfony 6.1., last on version 6.2..
I would be very grateful for a tip or a link to a working tutorial. Thanks
I have already created a user entity via make:user which has the following structure:
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\Entity(repositoryClass: UserRepository::class)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
private ?string $email = null;
#[ORM\Column]
private array $roles = [];
/**
* #var string The hashed password
*/
#[ORM\Column]
private ?string $password = null;
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* #see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->email;
}
/**
* #see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* #see PasswordAuthenticatedUserInterface
*/
public function getPassword(): string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* #see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
}
Then I created a controller for the /login and /logout routes with the following structure:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Entity\User;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
class UserLoginController extends AbstractController
{
#[Route('/login', name: 'app_login')]
public function index(#[CurrentUser] ?User $user): Response
{
if (null === $user) {
return $this->json([
'message' => 'missing credentials',
], Response::HTTP_UNAUTHORIZED);
}
return $this->json([
'message' => 'Welcome to your new controller!',
'path' => 'src/Controller/ApiLoginController.php',
'user' => $user->getUserIdentifier()
]);
}
}
And my configuration for it looks like this:
security:
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: "auto"
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
json_login:
check_path: /app_login
username_path: email
password_path: password
lazy: true
provider: app_user_provider
#custom_authenticator: App\Security\UserAuthenticator
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }

Conflicting Laravel controllers- one can call method the other gives non-static error

I've taken over the code from another developer, and I'm quite confused and stuck: one controller I can call the class method CLASSS::method perfectly OK. the other Controller has a copy of the orginal code and modified. On the second one, I get the "non-static method" error.
Call Chain:
Controller->Class->filtered results->Controller response
1A) (Working) Conttroller
<?php
namespace App\Http\Controllers\V1;
use App\Site as SiteClass;
use Facades\App\Site;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use App\{
Http\Controllers\Controller,
Http\Requests\SiteRequest,
Helper\ResourceTrait,
Assets,
Alerts,
Licensee,
Permits,
LandOwner,
Utility
};
use Illuminate\Support\Collection;
class SiteController extends Controller
{
private $obj;
public function __construct()
{
$this->obj = new SiteClass();
}
public function index(Request $request)
{
try
{
$data = Site::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
);
...removed some extra code that's not relevant ...
return response($data);
}
catch(\Exception $e)
{
Log::info('Create exception from here?' . $e);
return response(array('error'=>$e->getMessage()),422);
}
} // index
....
}
1B) (Working) Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Site extends BaseModel
{
protected $table = 'sites';
protected $fillable = [
"status","structureType","siteId","name","coverage","address","postCode", "subdistrict", "district", "region", "state", "country", "localCouncil", "latitude", "longitude", "dimensions",
"siteHandover", "startBilling", "utilityBillAcct", "utilityBillingAddress", "renewalTerm",
"capex", "opex", "siteManager", "siteManagerPhone", "siteManagerEmail", "siteOwnerManager", "siteOwnerManagerPhone", "siteOwnerManagerEmail"
];
...
// Working Static method call.
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
->orWhere($this->table.'.status','=',$search)
->orWhere($this->table.'.siteId','like','%'.$search.'%')
->orWhere($this->table.'.address','like','%'.$search.'%')
->orWhere($this->table.'.subdistrict','like','%'.$search.'%')
->orWhere($this->table.'.district','like','%'.$search.'%')
->orWhere($this->table.'.region','like','%'.$search.'%')
->orWhere($this->table.'.state','like','%'.$search.'%')
->orWhere($this->table.'.country','like','%'.$search.'%')
->orWhere($this->table.'.localCouncil','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('siteId','desc');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
2A) (Failing) Controller
<?php
namespace App\Http\Controllers\V1;
use App\{
Http\Controllers\Controller,
Helper\ResourceTrait,
Http\Requests\OrganisationRequest,
Organisation
};
use Illuminate\{
Http\Request,
Support\Facades\Config,
Support\Facades\Log
};
class OrganisationController extends Controller
{
private $org;
public function __construct()
{
$this->org = new Organisation();
}
public function index(Request $request)
{
try
{
//WORKAROUND: $this->org->... works
$data = Organisation::filter(
($request->has('sort')? $request->input('sort') : ''),
($request->has('filter')? $request->input('filter') : '')
); // FAILS with non-static method call error
return response($data);
}
catch(\Exception $e)
{
return response(array('error'=>$e->getMessage()),422);
}
} // index
}
...
2B) Failing Class
<?php
namespace App;
use Illuminate\Support\Facades\Config;
use \App\BaseModel;
class Organisation extends BaseModel
{
protected $table = 'organisation';
public function filter($sort = null, $search = null)
{
$data = $this;
// check if search variable not empty
if ($search != null)
{
$data = $data->where(function ($query) use ($search){
return $query->where($this->table.'.name','like','%'.$search.'%')
;
});
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
}
// check if sort variable not empty
if ($sort != null)
{
$sorts = explode('|', $sort);
$data = $data->orderBy($sorts[0],$sorts[1]);
}
else
{
$data = $data->orderBy('name');
}
// return data
return $data->paginate(Config::get('api.records'));
}
}
To my untutored eye, they look identical, yet one works and the other doesn't. Apologies in advance for the volume of code, but I don't know which parts are affecting what. I suspect it's somethng to do with an imported class, but I'm lost frankly :-D
Site has a Facade while Organisation does not.
Facades (from the docs) provide a "static" interface to classes that are available in the application's service container.

My PDO class returns Error on Execution

I finished transitioning to PDO and am modifying my system according to fatal errors that pop up.
ERR: Call to a member function execute() on a non-object in /home/a1933806/public_html/globals/server-bin/php/core.php
LINE: 43
This is my setup with affected line in bold:
class netCore {
private $armor;
private $boot;
private $dbHost = "*****.*******.com";
private $dbNAME = "********";
private $dbPASS = "********";
private $dbUSR = "********";
private $err;
private $state;
public function __construct() {
$bootloadr = "mysql:host=".$this->dbHost.";dbname=".$this->dbNAME.";charset=UTF8";
$opt = array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try {
$this->boot = new PDO($bootloadr, $this->dbUSR, $this->dbPASS, $opt);
} catch(PDOException $e) {
$this->err = "<b>Lebensborn® netCore™ Error:</b> An exception has been raised during Network-to-Database procedures.<br /><b>Message:</b> ".$e->getMessage().".";
}
}
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->state->bindValue($param, $value, $type);
}
public function exe() {
return $this->state->execute();
}
public function count() {
return $this->state->rowCount();
}
public function q($q) {
try {
$this->armor = $this->boot->prepare($q);
$this->state = $armor;
} catch(PDOException $e) {
$this->err = "<b>Lebensborn® netCore™ Error:</b> An exception has been raised during Network-to-Database procedures.<br /><b>Message:</b> ".$e->getMessage().".";
}
}
public function set() {
$this->exe();
return $this->state->fetchAll(PDO::FETCH_ASSOC);
}
public function single() {
$this->exe();
return $this->state->fetch(PDO::FETCH_ASSOC);
}
public function transBegin() {
return $this->boot->beginTransaction();
}
public function transCancel() {
return $this->boot->rollBack();
}
public function transEnd() {
return $this->boot->commit();
}
}

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");
}
}

Zend - Losing post values in Mapper

I seem to be losing my post data when passing it from my Controller to my Mapper to insert into my DB. I'm new to this and using the Guestbook template but modified it to be adding a "deal". This is what I have:
Controller
public function newAction()
{
$request = $this->getRequest();
$form = new Application_Form_Deal();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$posts = $form->getValues();
//print_r($posts);
$newdeal = new Application_Model_Deal($posts);
$mapper = new Application_Model_DealMapper();
$mapper->save($newdeal);
return $this->_helper->redirector('index');
}
}
$this->view->form = $form;
}
This is my Mapper
public function save(Application_Model_Deal $deal)
{
$data = array(
'dealname' => $deal->getDealName(),
'dealclient' => $deal->getDealClient(),
'dealtelephone' => $deal->getDealTelephone(),
'dealvalue' => $deal->getDealValue(),
'dealdescription' => $deal->getDealDescription(),
'dealcreated' => date('Y-m-d H:i:s'),
'dealmodified' => date('Y-m-d H:i:s'),
);
/*echo "<pre>";
print_r($data);
echo "</pre>";
exit();*/
if (null === ($dealid = $deal->getDealId())) {
unset($data['dealid']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('dealid = ?' => $dealid));
}
}
protected $_dealmodified;
protected $_dealcreated;
protected $_dealdescription;
protected $_dealvalue;
protected $_dealtelephone;
protected $_dealclient;
protected $_dealname;
protected $_dealid;
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid deal property');
}
$this->$method($value);
}
public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid deal property');
}
return $this->$method($value);
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setDealModified($ts)
{
$this->_dealmodified = $ts;
return $this;
}
public function getDealModified()
{
return $this->_dealmodified;
}
public function setDealCreated($ts)
{
$this->_dealcreated = $ts;
return $this;
}
public function getDealCreated()
{
return $this->_dealcreated;
}
public function setDealDescription($text)
{
$this->_dealdescription = (string) $text;
return $this;
}
public function getDealDescription()
{
return $this->_dealdescription;
}
public function setDealValue( $text)
{
$this->_dealvalue = $text;
return $this;
}
public function getDealValue()
{
return $this->_dealvalue;
}
public function setDealTelephone($text)
{
$this->_dealtelephone = $text;
return $this;
}
public function getDealTelephone()
{
return $this->_dealtelephone;
}
public function setDealClient($text)
{
$this->_dealclient = $text;
return $this;
}
public function getDealClient()
{
return $this->_dealclient;
}
public function setDealName($text)
{
$this->_dealname = $text;
return $this;
}
public function getDealName()
{
return $this->_dealname;
}
public function setDealId($dealid)
{
$this->_dealid = (int) $dealid;
return $this;
}
public function getDealId()
{
// $this->_dealid = (int) $value;
return $this->_dealid;
}
I am a complete loss as to why, when I print_r my $data var in the Mapper everything is gone.
Please help!
This looks odd $mapper->save($newdeal, $posts);
your api is save(Application_Model_Deal $deal)
so it should read $mapper->save($newdeal);.
if you really want to get a handle on mappers and models, these three links helped me alot:
http://survivethedeepend.com/
http://phpmaster.com/building-a-domain-model/
http://phpmaster.com/integrating-the-data-mappers/
You are after a specific work flow :
present form
collect from data (the $post)
validate $post data (if(isValid())
get valid and filtered form values ($form->getValues())
instantiate your deal object ($newdeal = new Application_Model_Deal($posts);)
save/update your deal with your mapper
on success redirect
once your deal object is created the $post data has no further value and the deal object is the important thing to think about. Hope this helps a bit.
Ok I think I found it:
your problem revolves around this $method = 'set' . ucfirst($key); this line will try and call $this->setProperty(); your getters and setters are set up camel case so they won't work. The easiest way to fix this is to rename your getters and setters to:
public function setDealmodified($ts)//not camel cased only first letter is capped.
{
$this->_dealmodified = $ts;
return $this;
}
or you have to camel case your array keys.
Your save() method in the mapper does not have a second argument which you used as your $post parameter.
Refactor:
public function save(Application_Model_Deal $deal, array $post)...