I am having a few difficulties with mysql and PDO.
I wish to insert a product into the database, however the product table contains foreign keys. Naturally, I will not know the Foreign key ID when inserting. Am I doing this right??? Is there a better way of tackling this problem?
TABLE Products
- Id PK AI int
- Name Varchar(20)
- CategoryId Int FK
- TypeId Int FK
TABLE Categories
- Id Int PK
- Cat varchar(20)
TABLE Types
- Id Int PK
Type varchar(20)
$type = 'Gloves'; $category = 'Clothing'; $sql = 'INSERT INTO Products SET Name = :name, CategoryId = :catId, TypeId = :typeId WHERE CategoryId IN (SELECT Id FROM Categories WHERE Cat = :category) AND TypeId IN (SELECT Id FROM Types WHERE Type = :type)' $stmt = $db->prepare($sql); $stmt->execute(array(':name' => 'Pink childrens gloves', ':category' => $category, ':type' => $type));
As mentioned in a comment below: Normally, I would be getting the ID from a select box. I cannot do this because it will be a script executing the query, not a user.