0

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:

title=products 

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.

1
  • conn_create() is a function I wrote that connects to the database I am using by grabbing my authentication from a file. That function is behaving as expected as I have been able to use it in many other SQL queries I have that are working properly. Commented Nov 16, 2016 at 0:19

1 Answer 1

1

This is your problem

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

Change it to

$result = $conn->query($query);
// -------------^  remove the $
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that worked. I knew it had to be something simple I was overlooking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.