Tesla51P Tesla51P - 9 months ago 37
MySQL Question

Using PHP to insert into SQL Table with Foreign Keys

I am trying to use PHP to insert data into a SQL table that contains 2 foreign keys. My table is laid out as follows:


columns = cart_id, prod_id // Both columns are foreign keys that come from another table.

I have been able to successfully insert the data in phpmyadmin, but whenever I try to insert inside my php script, I run into errors. The SQL query that phpmyadmin gives is

INSERT INTO `cart_prod` (`cart_id`, `prod_id`)
VALUES ('77717', '123456789');

However, when I copy and paste that query into my php code as follows, it does not work.

$conn = conn_create();

$query = "INSERT INTO cart_prod (cart_id, prod_id)
VALUES ('$this->cart_id', '$product_id');";

$result = $conn->$query($query);

Cart id is an attribute of the class that this code is contained within and product_id is a value that is passed through to the class function. I can copy and paste the values directly into my query and that still does not work.

I am using WAMPserver, and when I try to test this section of code, I get the following error:

Fatal error: Call to undefined method mysqli::INSERT INTO cart_prod(cart_id, prod_id) VALUES('77717', '123456789');() in C:\wamp64\www\php\customer.php on line 38

Both of my foreign keys have values in the other tables they are being pulled from. The database does not have a primary key. The way the database is supposed to work is that each row of cart_id will contain a product. All prod_id's associated with a particular cart_id would belong to that cart.

Ex. Database

cart_id prod_id
77717 123456789
77717 987654321
12345 113987454
12345 123456789

Am I doing something wrong with syntax in the query that I seem to be overlooking? Or is it something with the database that needs to be changed such as adding a primary key.

Answer Source

This is your problem

$result = $conn->$query($query);

Change it to

$result = $conn->query($query);
// -------------^  remove the $