如果代码中有任何错误,如何将值插入数据库 table?

How to insert value to the database table if their is any error, in the code?

让我考虑两个tables

部门:它有两列

-- id (primary key & auto increment)
-- name

-- logs :它有五列

            -- id (primary key & auto increment)
            -- class name
            -- function name
            -- error message
            -- date

现在我需要做的就是如果我在下面的代码中遇到任何错误,我的日志 table 应该更新为 各自的 class 名称、函数名称和消息。我该怎么做?

department.php

<?php
class Department
{
    public $db_connection = "";
    public function __construct()
    {
        $db_connection = new mysqli("localhost","root","","emp_app");
        if($db_connection->connect_error)
            die("connection failed".$db_connection->connect_error); 
    }   
    public function create($name)
    {
        try{
            if($this->db_connection){
                $sql_query = "insert into departments (name) values ('$name')";
                if($this->database_connection->query($sql_query) == True){
                    $result["status"] = 1;
                    $result["message"] = "Department '".$department_name."' successfully inserted";
                }
                else{
                    $result["status"] = 0;
                    $result["message"] = "Couldn't add to the list.Sorry";
                }
            }
            else{
                throw new Exception("Database connection doesn't exist");
            }
        }
        catch (Exception $error){
            $result["status"] = 0;
            $result["message"] = $error->getMessage();
        }
        return $result;
    }
}?> 

index.php

<?php 
include "department.php";
$connection = new Department();
$output = $connection->create("Testing");
if($output["status"] == 1){
    echo $output["message"];
}
else{   
    echo $output["message"];
    echo $output["message"];
}

?>

制作您自己的错误处理程序,并在其中将错误记录到日志文件中。发生错误时触发错误处理函数。

more info in php docs

有一个 class 包含一种方法,该方法执行 Insert 内容以记录到 table。使用很少的参数调用该方法,例如

if($this->database_connection->query($sql_query) == True){
$result["status"] = 1;
$result["message"] = "Department '".$department_name."' successfully inserted";
 }
  else{
        $result["status"] = 0;
        $result["message"] = "Couldn't add to the list.Sorry";
        // here query fails, so do like
        // Anotherclass.doLog($classname, $functionname, $date);
        // assign $classname, $functionname based on the class and function & for date use date() function
 }

Anotherclass中你可以有这样的方法,

 public function doLog($classname, $fname, $date)
   {

    // insert query here

    }