0
$this->db->query("INSERT INTO products 
                (name, price, description, stock) 
                VALUES ('$name', '$price', '$description', '$stock')");

$this->db->query("INSERT INTO products (category)
                SELECT id
                FROM categories
                WHERE category_name = '$category'");

These queries work fine if run individually, but how do I run them together? I am trying to add product data to a table and also get the category id and insert it at the same time.

0

1 Answer 1

1

In general, you can specify hardcoded values in the SELECT

INSERT INTO table1 (col1, col2, col3)
    SELECT id, 'string1', 'string2'
    FROM table2
    WHERE cond1 = val4;

Which will add the value if id and string1 and string2 into table1

In your case should be

INSERT INTO products (category, name, price, description, stock)
                SELECT id, '$name', '$price', '$description', '$stock'
                FROM categories
                WHERE category_name = '$category'
Sign up to request clarification or add additional context in comments.

Comments

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.