How to programmatically add product to Opencart database

usama sulaiman picture usama sulaiman · Jun 15, 2013 · Viewed 20.4k times · Source
  • I wonder if there is a special opencart function to add/edit a product to Opencart database programmatically using php/html form on front-end page (such as wordpress "wp_insert_post" function ) or I have to write all my code PHP way (insert into DB_TABLE .....)

  • Also which opencart db tables I have to use to add simple product information with an image, is it only product and product_description tables, of course i need the product to appear also in the admin page after adding it using front-end page

I really need some references to show me the way to do that

(I'm using opencart 1.5.1.3)

Answer

Jay Gilford picture Jay Gilford · Jun 15, 2013

You simply need to create an associate array of values to be passed to the addProduct() method in /admin/model/catalog/product.php. To load the model in your controller use

// Assoc array of data
$productData = array(
    'name' => 'Product Name Here',
    'model' => 'ABC123',
    ...
);

// Load model into memory if it isn't already
$this->load->model('catalog/product');

// Attempt to pass the assoc array to the add Product method
$this->model_catalog_product->addProduct($productData);

This is exactly what OpenCart does in the admin area, only that it uses the POSTed values from the form to pass as the array

Note that some values such as descriptions, images and so on are arrays within the data array itself and therefore need to be coded as such. If you want to take a look at what the model receives from the product add form, Open the model php file, find the addProduct() method and print_r the $data variable at the start of the method which will give you the full list of array keys, most of which are not required. See the form in the admin for which are. It's pretty easy to work out which field relates to which key in the array

More info on getting started as a developer in OpenCart