Trinity76
Trinity76

Reputation: 665

PHP how to var_dump an object in a function writing into database?

I use CodeIgniter and I have a function createRecord in a model:

public function createRecord($aRecordToSave) {
    $oLatestRecord = $this->getLatestRecord($aRecordToSave[$this->sForeignKey]);
    var_dump($oLatestRecord);
    $this->db->trans_begin();
    $this->db->where($this->sForeignKey, $aRecordToSave[$this->sForeignKey]);
    $this->db->update($this->sRecordsTable, array('latest' => 0));
  }

How can I display var_dump output, when the function is executed only by writing in the database and page is redirected instantly from edit by clicking save to show view?

Upvotes: 4

Views: 2360

Answers (2)

Martin
Martin

Reputation: 22760

If you want to only output the result of your var_dump

var_dump is usually used in a debugging context and not usually for a feeback message to user context.

So; if you want to feedback the message to the user, it's easiest to use a $_SESSION and dump the var using print_r().

Therefore:

public function createRecord($aRecordToSave) {
    ....
    $_SESSION['message'] = print_r($oLatestRecordSignature,true);
    ....
  }

Will save your message and you can then add code to your output page to display the message, for example:

if(!empty($_SESSION['message'])){
     print $_SESSION['messge'];
     unset($_SESSION['message]);
}

If you want to record the result of your var_dump and cease execution

Unlike print_r(), var_dump doesn't let you choose where the data is output.

So; if you want to feedback the message to debug, it's easiest to use the PHP errr_log and dump the var. It is better to store things in the error log rather than simply output errors to screen, as you can view how the error evolves as you make changes to the code with each execution.

Therefore:

public function createRecord($aRecordToSave) {
    ....
    error_log(print_r($oLatestRecordSignature,true));
    error_log(print_r(debug_backtrace(),true); //optional but useful
    exit; // cease script execution. 
    ....
  }

You can then read this detail in your error log.

Upvotes: 5

kkj
kkj

Reputation: 42

var_dump();die; should work just fine for this.

Upvotes: -2

Related Questions