I am using PHP and MySQL and I have run into a small problem. I have tried to research and figure out what to do, however, I just can’t figure it out. I would appreciate any help. Here is my problem…
I have 3 SQL tables:
Customers
cID (primaryKey)
email
name
password
...etc.
Products
pID (primaryKey)
Pname
Ptype
CustomerRequests
requestID(primarykey)
cID (foreign key references customer table)
pID (foreign key references products table)
quantityRequested
I have an HTML form that I am processing with PHP. This is like the request form, so the user logs in and fills in the request form. The fields on this form are like:
selecting product name, selecting quantity etc. This is done for e.g. $quantity=$_POST['quantity']… so basically the form data is stored inside the variables.
Now, here is the part that I’m stuck on. How do I carry out a SQL INSERT query so that the database knows what the cID and pID are? I.e. What the foreign key values are?
For example:
$insert = mysql_query(INSERT INTO CustomerRequests VALUES ('THIS WOULD BE BLANK AS ITS AUTOINCREMENTED PROMARY KEY FOR REQUEST ID','HOW WOULD I GET THE cID AUTOMATICALLY HERE','HOW WOULD I GET THE pID HERE','".$quantity."'))
The query stores the user input into the database using an INSERT query. However, since the customerID and productID are foreign keys in a different table how do i write the PHP query?
Thanks for the help and please get back to me if you need further information.
I’m not sure why you think you have a problem. The
cIDshould be known because the customer is logged in. ThepIDshould be known because your form should be using a dropdown list of products with thepIDbeing used as thevalue.Then it’s a simple matter of doing an
INSERTusing those values, i.e.In other words, these values are all known before they hit your form.
Don’t match product names with ID’s after the fact; that’s just adding extra work. If you have a value available then you should use it. Your form should already contain the association.
Create the dropdown based on a
SELECTquery from your Products table. Use thepIDfor thevalueand thepNamefor the content. That way, the data sent in the form is the foreign key you need in yourINSERT.Similarly, when you log your user in, get their
cIDand insert it into the session.One other note, cease from using PHP’s
mysql_family of functions. These are deprecated and due to be removed from a future release. They are prone to SQL Injection. You should be using eithermysqli_or PDO in your application. Both offer parameterized queries and prepared statement.