There are two tables: address and person. person_id (primary key, autoincrement) is a foreign key to address. I am trying to add an address record and person record from the same form but am getting this error.
Uncaught Error: Attempt to assign property "person_id" on null in
C:xampphtdocsappcontrollersMain.php:22 Stack trace: #0 [internal
function]: appcontrollersMain->insert() #1
C:xampphtdocsappcoreApp.php(52): call_user_func_array(Array,
Array) #2 C:xampphtdocsindex.php(4): appcoreApp->__construct() #3
{main} thrown in C:xampphtdocsappcontrollersMain.php on line 22
public function insert(){
if(isset($_POST['action'])){
$person = new appmodelsPerson();
$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');
}
Person insert method
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]);
}
Address insert
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]);
}
2
Answers
You have to use
mysqli insert_id
, after executing the insert command.insert_id
will give you the primary key of the insert.After
At no time do you use your
Address
model to insert the data into your address table.Modify your code by adding this line :