【发布时间】:2021-11-21 02:16:51
【问题描述】:
有两个表:地址和人员。 person_id(主键,自动增量)是要寻址的外键。我正在尝试从同一个表单中添加地址记录和人员记录,但出现此错误。
未捕获的错误:尝试在 null 上分配属性“person_id” C:\xampp\htdocs\app\controllers\Main.php:22 堆栈跟踪:#0 [内部 功能]:app\controllers\Main->insert() #1 C:\xampp\htdocs\app\core\App.php(52): call_user_func_array(Array, 数组)#2 C:\xampp\htdocs\index.php(4): app\core\App->__construct() #3 {main} 在第 22 行的 C:\xampp\htdocs\app\controllers\Main.php 中抛出
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]);
}
【问题讨论】:
-
你能检查一下person记录是否被插入到数据库吗?
-
是的,个人记录已添加到数据库中,并带有自动生成的 person_id,但地址记录不是。
-
$address->person_id = ...- 那么$address应该来自那个位置呢?你没有在方法内部创建它,它没有作为参数传入,你也没有从全局范围导入它。 -
@JessicaAlmany,您需要在第二个插入之前获取第一个插入的最后插入的 id。因为执行命令将只返回布尔值,即 true 或 false
标签: php sql database phpmyadmin