0

I am having a quite simple problem, but I cannot seem to understand where I am going wrong. I have two tables and I am just trying to set the primary key of the first table to be a field in the second table but keep receiving null in the database. Any help would be greatly appreciated, thank you for your time.

$createTable1 = "CREATE TABLE IF NOT EXISTS Customer (
  CustomerID INT(10) AUTO_INCREMENT PRIMARY KEY,
  gender VARCHAR(15) NOT NULL,
  title VARCHAR(10),
  firstname VARCHAR(30) NOT NULL,
  lastname VARCHAR(30) NOT NULL,
  email VARCHAR(50) NOT NULL ,
  phone VARCHAR(15) NOT NULL,
  cell VARCHAR(15) NOT NULL
)";

$createTable2 = "CREATE TABLE IF NOT EXISTS CustomerLocation (
  id INT(10) AUTO_INCREMENT PRIMARY KEY,
  CustomerID INT,
  `number` VARCHAR(10) NOT NULL,
  address VARCHAR(30) NOT NULL,
  city VARCHAR(20) NOT NULL,
  state VARCHAR(20) NOT NULL,
  country VARCHAR(25) NOT NULL,
  postcode VARCHAR(10) NOT NULL,
  latitude VARCHAR(15) NOT NULL,
  longitude VARCHAR(15) NOT NULL,
  `offset` VARCHAR(6) NOT NULL,
  `description` VARCHAR(50) NOT NULL,

  CONSTRAINT tt_1 FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID)

)";
  • What is the second table? You posted the same table twice. – Barmar Aug 12 '22 at 01:12
  • 1
    Foreign keys aren't filled in automatically. – Barmar Aug 12 '22 at 01:12
  • When you insert a customer location, how is it supposed to know which customer it belongs to? – Barmar Aug 12 '22 at 01:14
  • 1
    If you just inserted the customer, you can use `LAST_INSERT_ID()` to get the customer ID that was assigned, and use that when inserting into `CustomerLocation`. – Barmar Aug 12 '22 at 01:15
  • I posted the first table twice; it is corrected now. I want the primary key of the first table to be the foreign key in the second table. – imtryingman Aug 12 '22 at 01:16
  • You did that correctly. But you still have to fill in the foreign key explicitly, nothing will fill it in automatically. – Barmar Aug 12 '22 at 01:19

0 Answers0