I wrote a query that is throwing an error when it can’t find a record:
Error
Column ‘product_id’ cannot be null
MySQL
INSERT INTO orders (date, product_id, quantity)
VALUES ('11/29/2012', (
SELECT product_id FROM products WHERE product_name = 'Oranges'
), 12)
;
I’m actually iterating in my PHP and some of the product_name records are not going to exist.
Can I say somehow that if the subquery returns nothing, gracefully stop/abort so the PHP can keep iterating?
Try this:
If there is no matching product, the query will succeed but return no rows modified. If you wish you can read the number of rows modified from PHP when you execute the query.
Notice that if there are multiple products with
product_name = 'Oranges'you’ll get multiple rows inserted into your table.