Php - 无法创建新的数据库记录,因为主键为空(自动增量)

Php - cannot create new database record because primary key is null (autoincrement)

有两个表:address 和 person。 person_id(主键,自增)是外键地址。我正在尝试从同一表单添加地址记录和人员记录,但出现此错误。

Uncaught Error: Attempt to assign property "person_id" on null in C:\xampp\htdocs\app\controllers\Main.php:22 Stack trace: #0 [internal function]: app\controllers\Main->insert() #1 C:\xampp\htdocs\app\core\App.php(52): call_user_func_array(Array, Array) #2 C:\xampp\htdocs\index.php(4): app\core\App->__construct() #3 {main} thrown in C:\xampp\htdocs\app\controllers\Main.php on line 22

    public function insert(){
        if(isset($_POST['action'])){
            $person = new \app\models\Person();
            $person->first_name =($_POST['first_name']);
            $person->last_name =($_POST['last_name']);
            $person->notes =($_POST['notes']);
            $person->insert();

            $address->person_id = $person->person_id; //this is line 22
            $address->description =($_POST['description']);
            $address->street_address =($_POST['street_address']);
            $address->city =($_POST['city']);
            $address->province =($_POST['province']);
            $address->zip_code =($_POST['zip_code']);
            $address->country_code =($_POST['country_code']);
            $address->insert();         
            header('location:/Main/index');
        }else
            $this->view('Main/insert');
    }

人物插入法

    public function insert(){
        $SQL = 'INSERT INTO Person(person_id, first_name, last_name, `notes`) VALUES (:person_id,:first_name, :last_name, :notes)';
        $STMT = self::$_connection->prepare($SQL);
        $STMT->execute(['person_id'=>$this->person_id, 'first_name'=>$this->first_name, 'last_name'=>$this->last_name,'notes'=>$this->notes]);
    }

地址插入

    public function insert(){
        $SQL = 'INSERT INTO Address(person_id, description, street_address, city, province, zip_code, country_code) VALUES (:person_id, :description, :street_address, :city, :province, :zip_code, :country_code)';
        $STMT = self::$_connection->prepare($SQL);
        $STMT->execute(['person_id'=>$this->person_id, 'description'=>$this->description, 'street_address'=>$this->street_address, 'city'=>$this->city, 'province'=>$this->province, 'zip_code'=>$this->zip_code, 'country_code'=>$this->country_code]);
    }

您必须在执行插入命令后使用mysqli insert_idinsert_id 会给你插入的主键。

之后

$person->insert();
$address->person_id = $person->insert_id;

您绝不会使用 Address 模型将数据插入到您的 地址 table.

通过添加此行修改您的代码:

$address = new \app\models\Address(); //ADD THIS LINE
$address->person_id = $person->person_id;
//...