ethio
ethio

Reputation: 539

Run two queries, INSERT and INSERT INTO SELECT (php, mysql)

$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.

Upvotes: 0

Views: 1714

Answers (1)

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

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'

Upvotes: 1

Related Questions