让我考虑两张桌子

部门:有两列

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

-日志:它有五列
            -- id (primary key & auto increment)
            -- class name
            -- function name
            -- error message
            -- date

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

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"];
}

?>

最佳答案

有一个包含一个方法的类,该方法执行Insert东西记录到该表中。使用很少的参数调用该方法,例如,

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

    }

关于php - 如果代码中有任何错误,如何在数据库表中插入值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29696122/

10-12 14:49