PHP PDO fetchObject returns duplicated properties, half of them null [closed]

I’m trying to learn PHP and MySQL. I’ve got a database and some retrieval happening, but when I used fetchObject() I get 2 instances returned. First tried:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class Food {
// Properties
public $id;
public $version;
public $name;
public $solid;
public $servingtext;
public $servingmeasure;
public $servingamount;
private function __construct__() {}
public static function get_with_id ($dbconn,$id, $version) {
$stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;');
$stmt->execute([':Id' => $id, ':Version' => $version]);
return $stmt->fetchObject(__CLASS__);
// return $answer;
}
// Methods
function set_id($id){
$this->id = $id;
}
etc. with sets and gets
</code>
<code>class Food { // Properties public $id; public $version; public $name; public $solid; public $servingtext; public $servingmeasure; public $servingamount; private function __construct__() {} public static function get_with_id ($dbconn,$id, $version) { $stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;'); $stmt->execute([':Id' => $id, ':Version' => $version]); return $stmt->fetchObject(__CLASS__); // return $answer; } // Methods function set_id($id){ $this->id = $id; } etc. with sets and gets </code>
class Food {
  // Properties
  public $id;
  public $version;
  public $name;
  public $solid;
  public $servingtext;
  public $servingmeasure;
  public $servingamount;

  private function __construct__() {}

  public static function get_with_id ($dbconn,$id, $version) {
      $stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;');
      $stmt->execute([':Id' => $id, ':Version' => $version]);
      return  $stmt->fetchObject(__CLASS__);
    //   return $answer;
   }

  // Methods
  function set_id($id){
    $this->id = $id;
  }
   etc. with sets and gets

Called with

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>require "./templates/header.php";
try
{
include __DIR__ . '../../connection.php';
$conobj = new Connection();
$dbconn = $conobj->get_connection();
} catch (Throwable $t) {
error_log(__FILE__ . ':' . $t->getMessage());
echo 'Connection Error ' . $t->getMessage();
}
require "./models/food.php";
$food = Food::get_with_id ($dbconn,2,0);
var_dump($food);
</code>
<code>require "./templates/header.php"; try { include __DIR__ . '../../connection.php'; $conobj = new Connection(); $dbconn = $conobj->get_connection(); } catch (Throwable $t) { error_log(__FILE__ . ':' . $t->getMessage()); echo 'Connection Error ' . $t->getMessage(); } require "./models/food.php"; $food = Food::get_with_id ($dbconn,2,0); var_dump($food); </code>
require "./templates/header.php";

try 
{
    include __DIR__ . '../../connection.php';
    $conobj = new Connection();
    $dbconn = $conobj->get_connection();
} catch (Throwable $t) {
    error_log(__FILE__ . ':' . $t->getMessage());
    echo 'Connection Error ' . $t->getMessage();
}
require "./models/food.php";
$food = Food::get_with_id ($dbconn,2,0);
var_dump($food);

Result:

object(Food)#4 (14) { ["id"]=> NULL ["version"]=> NULL ["name"]=> NULL ["solid"]=> NULL ["servingtext"]=> NULL ["servingmeasure"]=> NULL ["servingamount"]=> NULL ["Id"]=> int(2) ["Version"]=> int(0) ["Name"]=> string(35) "Sanitarium Weet-Bix Blends Hi-Bran+" ["Solid"]=> int(1) ["ServingText"]=> string(28) "1 serving = 40g (2 biscuits)" ["ServingMeasure"]=> string(1) "g" ["ServingAmount"]=> int(40) }

There should be just 7 fields, but the first set are all NULL and then there’s the object I’m hoping for.

I tried..

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?php
class Food {
// Properties
public $id;
public $version;
public $name;
public $solid;
public $servingtext;
public $servingmeasure;
public $servingamount;
private function __construct__() {}
// Methods
function set_id($id){
$this->id = $id;
}
</code>
<code><?php class Food { // Properties public $id; public $version; public $name; public $solid; public $servingtext; public $servingmeasure; public $servingamount; private function __construct__() {} // Methods function set_id($id){ $this->id = $id; } </code>
<?php
class Food {
  // Properties
  public $id;
  public $version;
  public $name;
  public $solid;
  public $servingtext;
  public $servingmeasure;
  public $servingamount;

  private function __construct__() {}

  // Methods
  function set_id($id){
    $this->id = $id;
  }

with

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?php
require "./templates/header.php";
try
{
include __DIR__ . '../../connection.php';
$conobj = new Connection();
$dbconn = $conobj->get_connection();
} catch (Throwable $t) {
error_log(__FILE__ . ':' . $t->getMessage());
echo 'Connection Error ' . $t->getMessage();
}
require "./models/food2.php";
$id = 2;
$version = 0;
$stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;');
$stmt->execute([':Id' => $id, ':Version' => $version]);
$food = $stmt->fetchObject('Food');
var_dump($food);
</code>
<code><?php require "./templates/header.php"; try { include __DIR__ . '../../connection.php'; $conobj = new Connection(); $dbconn = $conobj->get_connection(); } catch (Throwable $t) { error_log(__FILE__ . ':' . $t->getMessage()); echo 'Connection Error ' . $t->getMessage(); } require "./models/food2.php"; $id = 2; $version = 0; $stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;'); $stmt->execute([':Id' => $id, ':Version' => $version]); $food = $stmt->fetchObject('Food'); var_dump($food); </code>
<?php
require "./templates/header.php";

try 
{
    include __DIR__ . '../../connection.php';
    $conobj = new Connection();
    $dbconn = $conobj->get_connection();
} catch (Throwable $t) {
    error_log(__FILE__ . ':' . $t->getMessage());
    echo 'Connection Error ' . $t->getMessage();
}
require "./models/food2.php";
$id = 2;
$version = 0;
$stmt = $dbconn->prepare('SELECT * FROM Foods WHERE Id = :Id and Version = :Version;');
$stmt->execute([':Id' => $id, ':Version' => $version]);
$food = $stmt->fetchObject('Food');
var_dump($food);

Same result. Then with the same Food class tried:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?php
require "./templates/header.php";
try
{
include __DIR__ . '../../connection.php';
$conobj = new Connection();
$dbconn = $conobj->get_connection();
} catch (Throwable $t) {
error_log(__FILE__ . ':' . $t->getMessage());
echo 'Connection Error ' . $t->getMessage();
}
require "./models/food2.php";
$id = 2;
$version = 0;
$food = $dbconn->query('SELECT * FROM Foods WHERE Id = ' . $id . ' AND Version = ' . $version . ';')->fetchObject('Food');
var_dump($food);
</code>
<code><?php require "./templates/header.php"; try { include __DIR__ . '../../connection.php'; $conobj = new Connection(); $dbconn = $conobj->get_connection(); } catch (Throwable $t) { error_log(__FILE__ . ':' . $t->getMessage()); echo 'Connection Error ' . $t->getMessage(); } require "./models/food2.php"; $id = 2; $version = 0; $food = $dbconn->query('SELECT * FROM Foods WHERE Id = ' . $id . ' AND Version = ' . $version . ';')->fetchObject('Food'); var_dump($food); </code>
<?php
require "./templates/header.php";

try 
{
    include __DIR__ . '../../connection.php';
    $conobj = new Connection();
    $dbconn = $conobj->get_connection();
} catch (Throwable $t) {
    error_log(__FILE__ . ':' . $t->getMessage());
    echo 'Connection Error ' . $t->getMessage();
}
require "./models/food2.php";
$id = 2;
$version = 0;
$food = $dbconn->query('SELECT * FROM Foods WHERE Id = ' . $id . ' AND Version = ' . $version . ';')->fetchObject('Food');
var_dump($food);

Again, the result with 2 entries.

Please can someone help with why I’m getting the NULLs version first. I don’t want or need it. Happy to be told it’s a newbie error! I have had plenty of success retrieving arrays but would like to go down the OO path.

Thanks, Paul

PHP 8.1.30, MySQL 9.1.0 and NGINX 1.27.2 in a Docker container

2

fetchObject() generates the class and gives you the first 7 columns of null, as you added them on the class Food, and they default to NULL

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Your properties, they all get NULL
public $id;
public $version;
public $name;
public $solid;
public $servingtext;
public $servingmeasure;
public $servingamount;
</code>
<code>// Your properties, they all get NULL public $id; public $version; public $name; public $solid; public $servingtext; public $servingmeasure; public $servingamount; </code>
// Your properties, they all get NULL
public $id;
public $version;
public $name;
public $solid;
public $servingtext;
public $servingmeasure;
public $servingamount;

then the fetchObject() injects more variables: the columns of the result query also turns into class properties and makes it seems like its has duplicated, but we can trace it from the results of the vardump().

id duplicates with Id

version duplicates with Version

name duplicates with Name

Make the public properties variables match the column names you get on your query. From id to Id, servingtext to ServingText, etc.

Or find a way to generate the class without using fetchObject().

https://www.php.net/manual/en/pdostatement.fetchobject.php

New contributor

lemon8de is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật