Missing Argument in for __construct - php

I get this error where I run :
$db = new PDO('mysql:host=localhost;dbname=MYDATABASE', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$Manager = new CompanyManager($db);
$Manager->getList();
ERROR :
Warning: Missing argument 2 for Company::__construct(), called in /.../CompanyManager.class.php on line 53 and defined in /.../Company.class.php on line 17
Here is the part of CompanyManager.class.php :
public function getList()
{
$Company = array();
$q = $this->_db->query('SELECT id, statut, company, activity, source, secteur, comments, offer_date, entry_date, type_ope, gestionnaire, next_step FROM prospect ORDER BY id');
while ($donnees = $q->fetch(PDO::FETCH_ASSOC))
{
$Company[] = new Company($donnees);
}
return $Company;
}
And here is Company.class.php (interesting part) :
<?php
class Company
{
private $_id;
private $_statut;
private $_company;
private $_activity;
private $_source;
private $_secteur;
private $_comments;
private $_offerDate;
private $_entryDate;
private $_typeOpe;
private $_gestionnaire;
private $_nextStep;
public function __construct($id, $statut, $company, $activity, $source, $secteur, $comments, $offerDate, $entryDate, $typeOpe, $gestionnaire, $nextStep)
{
$this->setId($id);
$this->setStatut($statut);
$this->setCompany($company);
$this->setActivity($activity);
$this->setSource($source);
$this->setSecteur($secteur);
$this->setComments($comments);
$this->setOfferDate($offerDate);
$this->setEntryDate($entryDate);
$this->setTypeOpe($typeOpe);
$this->setGestionnaire($gestionnaire);
$this->setNextStep($nextStep);
}
BIG thanks for everyone who gonna try to give me a hand ;-)

public function getList()
{
$Company = array();
$q = $this->_db->query('SELECT id, statut, company, activity, source, secteur, comments, offer_date, entry_date, type_ope, gestionnaire, next_step FROM prospect ORDER BY id');
while ($donnees = $q->fetch(PDO::FETCH_ASSOC))
{
$Company[] = new Company($donnees['id'], $donnees['statut'], $donnees['company'], $donnees['activity'], $donnees['source'], .....);
}
return $Company;
}
Otherwise you can do this
public function __construct(array $data) {
$this->setId($data['id']);
.
.
.
.
}

Well your Company class expects all the parameters in the __construct() parameter list to be passed. None of them are optional.
It looks like you are passing an array to your Company class at the minute, you need to pass each value according to your parameter list.

You have to implicitly pass variables to Company's constructor:
public function getList()
{
$Company = array();
$q = $this->_db->query('SELECT id, statut, company, activity, source, secteur, comments, offer_date, entry_date, type_ope, gestionnaire, next_step FROM prospect ORDER BY id');
while (list($id, $status, $company, /*etc*/) = $q->fetch(PDO::FETCH_ASSOC))
{
$Company[] = new Company($id, $status, $company, /*etc*/);
}
return $Company;
}

Related

Data Model - How to define two model classes, and property method with a 1 to many relationship between them?

This Question is two-fold.
1)
Two models exist in my code with 1-To-many relationship (1 user has many action items). How do I set up this connection in a PHP class?
2)
One of the models, actionitem, needs a property function to produce a full name, (Last, First) of a actionitem made up of 4 types of users this property method should really come from (depend on) user determined by id.
How do I accomplish this objective?
<?php
namespace data\model;
class actionitem {
//Users
public $assignorid;
public $ownerid;
public $altownerid;
public $approverid;
//Additional Attributes
public $actionitemtitle;
public $actionitemstatement;
//Property Function 1
//How do I create the property function for $assignorid?
public function getAssignor(){
return ??
}
}
Problem is I have the property function specified in my user class
<?php
namespace data\model;
class user {
public $userid;
public $userlastname;
public $userfirstname;
//Property Function 2
public function getUserLastFirst(){
return trim($this->userlastname, ', ', $this->userfirstname);
}
}
Mapper class
<?php
class actionitems {
private $db = null;
public function __construct(PDO $db){
$this->db = $db;
}
protected function __populateFromCollection($results){
$return = array();
foreach($results as $result){
$return = $this->mapFromArray($result);
}
return $return;
}
public function mapFromArray($array, \data\model\actionitem $actionitem = null){
if (is_null($actionitem)) $actiontiem = new actionitem();
//Mapping code
if (is_null($array['assignor.lastname'])) $actionitem->assignorlastname = $array['assignor.lastname'];
if (is_null($array['assignor.firstname'])) $actionitem->assignorfirstname = $array['assignor.firstname'];
if (is_null($array['owner.lastname'])) $actionitem->ownerlastname = $array['owner.lastname'];
if (is_null($array['owner.firstname'])) $actionitem->ownerfirstname = $array['owner.firstname'];
if (is_null($array['altowner.lastname'])) $actionitem->altownerlastname = $array['altowner.lastname'];
if (is_null($array['altowner.firstname'])) $actionitem->altownerfirstname = $array['altowner.firstname'];
if (is_null($array['approver.lastname'])) $actionitem->altownerlastname = $array['approver.lastname'];
if (is_null($array['approver.firstname'])) $actionitem->approverfirstname = $array['approver.firstname'];
}
public function get($id){
}
public function getAll($params = [])
{
$whereStrings = $whereParams = array();
if (isset($params['Keyword'])){
$searchCols =
[
'assignor.lastname',
'assignor.firstname',
'owner.lastname',
'owner.firstname',
'altowner.lastname',
'altowner.firstname',
'approver.lastname',
'approver.firstname',
'actionitemtitle',
'criticality',
'actionitemstatement',
'closurecriteria',
'closurestatement',
'rejectionjustification',
'ownernotes',
'approvercomments',
'notes'
];
foreach ($searchCols as $col){
$whereStrings[] = "$col like ?";
$whereParams[] = $params['Keyword'];
}
}
$sql = "select
assignor.lastname AS assignorlastname,
assignor.firstname AS assignorfirstname,
owner.lastname AS ownerlastname,
owner.firstname AS ownerfirstname,
altowner.lastname AS altownerlastname,
altowner.firstname AS altownerfirstname,
approver.lastname AS approverlastname,
approver.firstname AS approverfistname,
a.*
from actionitems a
inner join users assignor
ON a.assignorid = assignor.userid
inner join users owner
ON a.approverid = owner.userid
inner join users altowner
ON a.altownerid = altowner.userid
inner join users approver
ON a.approverid = approver.userid";
if (!empty($whereStrings)){
$sql .= " where " . implode(' AND ' . $whereStrings);
}
if (isset($params['limit'])){
$sql .= " limit " . intval($params['limit']);
}
$statement = $this->db->prepare($sql);
$statement->execute($whereParams);
$resuls = $statement->fetchAll();
return $this->__populateFromCollection($results);
}
}

Call to a member function show() on string on line 15

It worked a week before, I check if the objects are being defined with function class_exists() and they are both fine.
My error:
Call to a member function show() on string on line 15
Which is a function of class $logged_user in profile.php
echo $logged_user->show("Email");
My object $logged_user looks like this:
class LOGGED_USER
{
private $DB;
private $ID;
private $Firstname;
private $Surname;
private $DisplayName;
private $Gender;
private $Birth;
private $Email;
private $Level;
private $FolderPath;
private $LastLogin;
private $LastIP;
private $LevelWord;
private $ProfilePicture;
private $ProfilePictureID;
function __construct($DB_con, $ID, $Fname, $Srname, $Email, $Level, $FolderPath, $LastLogin, $LastIP, $Gender, $Birth, $DisplayName, $ProfilePicture, $ProfilePictureID){
$BirthDay = strtotime($Birth);
$this->DB = $DB_con;
$this->ID = $ID;
$this->Firstname = $Fname;
$this->Surname = $Srname;
$this->Gender = $Gender;
$this->Birth = date("d-m-Y", $BirthDay);
$this->Email = $Email;
$this->Level = $Level;
$this->FolderPath = $FolderPath;
$this->LastLogin = $LastLogin;
$this->LastIP = $LastIP;
$this->LevelWord = $this->sayLevel($Level);
$this->DisplayName = $DisplayName;
$this->ProfilePicture = $ProfilePicture;
$this->ProfilePictureID = $ProfilePictureID;
}
//Function for calling "private" data
public function show($atribut){
return $this->$atribut;
}
This object in $logged_user is beeing created in this object $user which works for registration and stuff for trying things as annonymous:
class USER
{
private $DB;
function __construct($DB_con)
{
$this->DB = $DB_con;
}
//Function for creating LOGGED_USER
public function useFactory($id){
require_once "logged_user.php";
$sql = $this->DB->prepare("SELECT us.ID, us.Firstname, us.Surname, us.Email, us.Level, us.Gender, us.Email, us.DisplayName, us.Birth, um.FolderHash, um.LastLogin, um.LastIP, uc.ProfilePictureID, up.Name, up.ID FROM Users AS us JOIN UsersMeta AS um ON us.ID = um.UsersID JOIN UsersConfig AS uc ON us.ID = uc.UsersID JOIN UsersPictures AS up ON up.ID = uc.ProfilePictureID WHERE us.ID = :id LIMIT 1");
$sql->execute(array(':id' => $id));
$sqlResult = $sql->fetchAll(PDO::FETCH_ASSOC);
if(!empty($sqlResult)){
foreach($sqlResult as $data){
return new LOGGED_USER($this->DB, $id, $data["Firstname"], $data["Surname"], $data["Email"], $data["Level"], $data["FolderHash"], $data["LastLogin"], $data["LastIP"], $data["Gender"], $data["Birth"], $data["DisplayName"], $data["Name"], $data["ID"]);
}
}else{
return "Prázdno!";
}
}
And here I am creating the $logged_userand trying to call function show():
session_start();
require_once "../config.php";
require_once "../objects/user.php";
$userFactory = new USER($db);
$userFactory->is_loggedin();
$logged_user = $userFactory->useFactory($_SESSION["user_session"]); //Returns new class (LOGGED_USER)
echo $logged_user->show("Email");
There is no need to fetchAll in your factory, as your criteria are id (the result always should be zero or one records). If you have no user with such id return null, so replace this:
$sqlResult = $sql->fetchAll(PDO::FETCH_ASSOC);
if(!empty($sqlResult)){
foreach($sqlResult as $data){
return new LOGGED_USER($this->DB, $id, $data["Firstname"], $data["Surname"], $data["Email"], $data["Level"], $data["FolderHash"], $data["LastLogin"], $data["LastIP"], $data["Gender"], $data["Birth"], $data["DisplayName"], $data["Name"], $data["ID"]);
}
}else{
return "Prázdno!";
}
with this:
$data = $sql->fetch(PDO::FETCH_ASSOC);
if (empty($data)) {
return null;
}
return new LOGGED_USER(
$this->DB,
$id, $data["Firstname"],
$data["Surname"],
$data["Email"],
$data["Level"],
$data["FolderHash"],
$data["LastLogin"],
$data["LastIP"],
$data["Gender"],
$data["Birth"],
$data["DisplayName"],
$data["Name"],
$data["ID"]
);
Then in your code check if logged_user is null:
if ($logged_user = $userFactory->useFactory($_SESSION["user_session"])) {
echo $logged_user->show("Email");
}

PHP-OOP | Not accessing database

I'm trying to make this code access a certain row in the database and pull "title" from it to update public $Title in the UserBlog class, but, it's not doing so.
The database connection is definitely working as it worked procedually, but OOP is messing it up.
$ID = $db->real_escape_string(strip_tags(stripslashes($_GET['ID']))); // Page ID
class UserBlog
{
public $Title;
public $BannerImage;
public $ID;
public function GenerateBlog() {
$FetchBlogDetails = mysqli_query($db, "SELECT * FROM UserBlogs WHERE ID = '$this->ID'");
$FBL = mysqli_fetch_object($FetchBlogDetails);
$this->Title = $FBL->Title;
}
public function FetchBlog() {
return $this->Title;
return $this->ID;
}
};
$GetBlog = new UserBlog();
$GetBlog->ID = $ID;
$GetBlog->GenerateBlog();
echo $GetBlog->Title;
echo $GetBlog->ID;
$db doesn't exist in the scope of your method. You could inject it when calling the method.
class UserBlog
{
public $Title;
public $BannerImage;
public $ID;
public function GenerateBlog($db) {
$FetchBlogDetails = mysqli_query($db, "SELECT * FROM UserBlogs WHERE ID = '$this->ID'");
$FBL = mysqli_fetch_object($FetchBlogDetails);
$this->Title = $FBL->Title;
}
//...
}
$GetBlog = new UserBlog();
$GetBlog->ID = $ID;
$GetBlog->GenerateBlog($db);

Declaring Query Objects in PHP Class Methods

I am in the process of building an object-oriented forms system. I am putting together a User class which contains about eight functions. Each function contains a MySQL query for which an object of the Query class must be instantiated.
Is there any way to keep from having to declare a new object every single time? It occurs to me that might bog down the server at some point.
The role of the User class is to extract information about the user from the database (name, email, etc). That data is then used throughout the system including to authenticate roles. Here is the User class:
class User{
protected $user_id;
protected $session_hash;
protected $user_username;
protected $user_email;
protected $user_role_id;
protected $user_role_name;
protected $user_first_name;
protected $user_last_name;
public function __construct($user_id, $session_hash){
$this->user_id = $user_id;
$this->session_hash = $session_hash;
}
public function __get($name){
return $this->name;
}
public function __set($name, $value){
$this->$name = $value;
}
public function getLoggedUserInfo(){
global $db;
$query = new Query($db->link);
if($user_matches = $query->select("SELECT name, mail FROM ".TABLE_PREFIX.".d7_users WHERE uid = '".$this->user_id."'")){
$this->user_username = $user_matches[0]['name'];
$this->user_email = $user_matches[0]['mail'];
$this->user_role_id = $this->getLoggedUserRoleId($this->user_id);
$this->user_role_name = $this->getLoggedUserRoleName($this->user_role_id);
$this->user_first_name = $this->getLoggedUserFirstName($this->user_id);
$this->user_last_name = $this->getLoggedUserLastName($this->user_id);
$user_information_arr = array(
'user_id' => $this->user_id,
'user_username' => $this->user_username,
'user_first_name' => $this->user_first_name,
'user_last_name' => $this->user_last_name,
'user_email' => $this->user_email,
'user_role_id' => $this->user_role_id,
'user_role_name' => $this->user_role_name,
);
return $user_information_arr;
}
return false;
}
private function getLoggedUserRoleId($user_id){
global $db;
$query = new Query($db->link);
if($role_id_matches = $query->select("SELECT rid FROM ".TABLE_PREFIX.".d7_users_roles WHERE uid= '".$user_id."'")){
$this->user_role_id = $role_id_matches[0]['rid'];
return $this->user_role_id;
}
return false;
}
private function getLoggedUserRoleName($role_id){
global $db;
$query = new Query($db->link);
if($role_name_matches = $query->select("SELECT name FROM ".TABLE_PREFIX.".d7_role WHERE rid = '".$role_id."'")){
return $role_name_matches[0]['name'];
}
return false;
}
private function getLoggedUserFirstName($user_id){
global $db;
$query = new Query($db->link);
if($first_name_matches = $query->select("SELECT field_first_name_value FROM ".TABLE_PREFIX.".d7_field_revision_field_first_name WHERE entity_id='".$user_id."'")){
return $first_name_matches[0]['field_first_name_value'];
}
return false;
}
private function getLoggedUserLastName($user_id){
global $db;
$query = new Query($db->link);
if($last_name_matches = $query->select("SELECT field_last_name_value FROM ".TABLE_PREFIX.".d7_field_revision_field_last_name WHERE entity_id='".$user_id."'")){
return $last_name_matches[0]['field_last_name_value'];
}
return false;
}
}
Pass the query object from an existing instance into the constructor of the User class.
protected $queryObject;
public function __construct($user_id, $session_hash, Query $query = NULL){
$this->user_id = $user_id;
$this->session_hash = $session_hash;
$this->queryObject = $query;
}

I can not add array from PDO to constructor PHP

I have probleme when i want add array from PDO to contructor of class news :
class News{
protected $erreurs = array(),
$id,
$auteur,
$titre,
$contenu;
public function __News(array $donnees){
$this->hydrate($donnees);
}
public function hydrate(array $donnees)
{
foreach ($donnees as $key => $value)
{
$method = 'set'.ucfirst($key);
if (method_exists($this, $method))
{
$this->$method($value);
}
}
}
Class Manager with function get news by id :
public function getUnique($id){
$id = (int)$id;
$sql = $this->db->prepare('SELECT id, auteur, titre, contenu FROM news WHERE id = ?');
$sql->bindParam('1', $id);
$sql->execute();
$mang = $sql->fetch(PDO::FETCH_ASSOC);
return new News($mang);
}
And index. php
$db = new PDO('mysql:host=localhost;dbname=new', 'root','');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$manager = new Manager($db);
$uniqueNews = $manager->getUnique(2);
echo 'id : '.$uniqueNews->getAuteur();
But i don't know why the value of auteur do not display . If I'm going about this contructor completely wrong, please point me in the right direction. Thanks.
The constructor of a class should be either __construct() or a method named after the class. I prefer the first option. The second option is for legacy code.
class News{
public function __construct(array $donnees){
// This is where your constructor code goes
}
}
Your constructor should be called __construct()
class News{
protected $erreurs = array(),
$id,
$auteur,
$titre,
$contenu;
public function __construct(array $donnees){
$this->hydrate($donnees);
}
}

Categories