0

I have a sql request in PHP, the result of this query is put in class variable But when tis request return no result, I would like have a null value in variable, for the moment I have a false boolean returned.

Could you help me ? Thank you

<?php 
class test
{
    const table_name = 'test_table';

    protected $Id;
    protected $Nom;
  
    public static function byId($id)
    {
        $values = array
        (
            ':Id' => $id,
        );
        
        $sql = 'SELECT *FROM '.self::table_name.' WHERE Id=:Id';
    
        $QueryPrep =  self::getInstance()->prepare($sql);
        if(empty($param))
        {
             $resultQuery = $QueryPrep->execute();
        }
 else
 {
     $resultQuery = $QueryPrep->execute($values);
 }
    
        if ($resultQuery !=false)
        {
            $res = $resultQuery->fetchObject(__CLASS__);
            return $res; 
        }
        else
        {
            return false;
        }
    } 

    public function get_Id()
    {
        return $this->Id;
    } 
}

$cmd_device_id = null;

$cmdDeviceObject = new test();
$cmd_device =  $cmdDeviceObject->byId(999);
$cmd_device_id = $cmd_device->get_Id();
echo "cmd_device_id = ".var_dump($cmd_device_id);

?>
  • So just return a null instead of false. `else { return null; }` – RiggsFolly Sep 04 '18 at 20:16
  • `$params` I think was intended to be a function parameter? And does not exist anywhere. Although it does not affect the execution much anyway – RiggsFolly Sep 04 '18 at 20:22
  • If you tidy up your logic, you will understand whats going on and so will we – RiggsFolly Sep 04 '18 at 20:23
  • Possible duplicate of [Call to a member function execute() on boolean in](https://stackoverflow.com/questions/35132451/call-to-a-member-function-execute-on-boolean-in) – Progman Sep 05 '18 at 09:33

1 Answers1

0

This return null if the $res has no result.

 if ($resultQuery !=false)
    {
        $res = $resultQuery->fetchObject(__CLASS__);
        return $res ?? null; 
    }
ogastonc
  • 36
  • 1
  • 5
  • I have try : `if ($resultQuery !=false) { return $res ?? null; } else { return null; }` And I have always the same error : PHP Fatal error: Uncaught Error: Call to a member function get_Id() on boolean – antoine durozo Sep 05 '18 at 06:45