2

I have the following select statement which I am constructing a user object:

$stmt = $conn->prepare("SELECT user.User_ID, user.User_Name
        FROM user");
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_CLASS| PDO::FETCH_PROPS_LATE,'User'); 

I have the following class in a separate file, included with - require "User.php":

class User
{
private $User_ID;
private $User_Name;

public function __construct($User_ID, $User_Name)
{
   $this->User_ID = $User_ID;
   $this->User_Name =$User_Name;
}    

I get the following warnings and notices -

Warning: Missing argument 1 for User::__construct()
Notice: Undefined variable: User_ID

It works fine but I turned on warnings etc as I am tidying up my code.

I have looked at other questions on here but the solutions don't seem to help and thought a fresh pair of eyes could help. A thought I had was I should have been passing an array in the setFetchMode() as the documentation states but that still seems to cause issues.

What is the correct way to create a class in PDO?

4
  • 2
    You're missing a "); on your prepare() call, which I'm hoping is just a typo while entering the question here... Commented Apr 22, 2015 at 17:40
  • @MarcB Thanks - yes just a typo Commented Apr 22, 2015 at 17:41
  • 1
    possible duplicate of PDO using PDO::FETCH_PROPS_LATE and __construct() call? Commented Apr 22, 2015 at 17:44
  • I hope you're not writing your own ORM when there's several out there like Doctrine, Propel or the sort that ships with a development framework like Laravel. Commented Apr 23, 2015 at 18:33

1 Answer 1

1

If you use arguments to User constructor, you need to use the third parameter in setFetchMode

public bool PDOStatement::setFetchMode ( int $PDO::FETCH_CLASS , string $classname , array $ctorargs )

In your case

$stmt->setFetchMode(PDO::FETCH_CLASS| PDO::FETCH_PROPS_LATE,'User',
array('User_ID','User_name'));    

or just provide default values for the constructor.

See the reference.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.