How to use custom query mysql in magento2

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get(‘Magento\Framework\App\ResourceConnection’);
$connection = $resource->getConnection();
$tableName = $resource->getTableName(’employee’); //gives table name with prefix

//Select Data from table
$sql = “Select * FROM ” . $tableName;
$result = $connection->fetchAll($sql); // gives associated array, table fields as key in array.

//Delete Data from table
$sql = “Delete FROM ” . $tableName.” Where emp_id = 10″;
$connection->query($sql);

//Insert Data into table
$sql = “Insert Into ” . $tableName . ” (emp_id, emp_name, emp_code, emp_salary) Values (”,’XYZ’,’ABD20′,’50000′)”;
$connection->query($sql);

//Update Data into table
$sql = “Update ” . $tableName . “Set emp_salary = 20000 where emp_id = 12”;
$connection->query($sql);

Update Custom Field value woocommerce

$product = wc_get_product( $product_id );
//echo $csvpro[7].’
‘; exit;
$product->update_meta_data( ‘ean’,sanitize_text_field( $csvpro[7] ));
$product->update_meta_data( ‘grossweight’, sanitize_text_field( $progrossweight ) );
$product->update_meta_data( ‘expectedinweek’, sanitize_text_field( $proexpectedinweek ) );
$product->update_meta_data( ‘demostock’, sanitize_text_field( $prodemostock ) );

$product->save();

How to Add a WooCommerce Product Programmatically

The first step is to initialize the Product Class Object.

For Simple Product use the below Code:

$objProduct = new WC_Product();
and for variable product use below line of code.

$objProduct = new WC_Product_Variable();

Next step is to set the meta Properties like name, price etc and variants data (in case of variable product).

$objProduct->set_name(“Product Title”);
$objProduct->set_status(“publish”); // can be publish,draft or any wordpress post status
$objProduct->set_catalog_visibility(‘visible’); // add the product visibility status
$objProduct->set_description(“Product Description”);
$objProduct->set_sku(“product-sku”); //can be blank in case you don’t have sku, but You can’t add duplicate sku’s
$objProduct->set_price(10.55); // set product price
$objProduct->set_regular_price(10.55); // set product regular price
$objProduct->set_manage_stock(true); // true or false
$objProduct->set_stock_quantity(10);
$objProduct->set_stock_status(‘instock’); // in stock or out of stock value
$objProduct->set_backorders(‘no’);
$objProduct->set_reviews_allowed(true);
$objProduct->set_sold_individually(false);
$objProduct->set_category_ids(array(1,2,3)); // array of category ids, You can get category id from WooCommerce Product Category Section of WordPress Admin

Below code is used if you want to upload images of product

function uploadMedia($image_url){
require_once(‘wp-admin/includes/image.php’);
require_once(‘wp-admin/includes/file.php’);
require_once(‘wp-admin/includes/media.php’);
$media = media_sideload_image($image_url,0);
$attachments = get_posts(array(
‘post_type’ => ‘attachment’,
‘post_status’ => null,
‘post_parent’ => 0,
‘orderby’ => ‘post_date’,
‘order’ => ‘DESC’
));
return $attachments[0]->ID;
}
// above function uploadMedia, I have written which takes an image url as an argument and upload image to wordpress and returns the media id, later we will use this id to assign the image to product.
$productImagesIDs = array(); // define an array to store the media ids.
$images = array(“image1 url”,”image2 url”,”image3 url”); // images url array of product
foreach($images as $image){
$mediaID = uploadMedia($image); // calling the uploadMedia function and passing image url to get the uploaded media id
if($mediaID) $productImagesIDs[] = $mediaID; // storing media ids in a array.
}
if($productImagesIDs){
$objProduct->set_image_id($productImagesIDs[0]); // set the first image as primary image of the product

//in case we have more than 1 image, then add them to product gallery.
if(count($productImagesIDs) > 1){
$objProduct->set_gallery_image_ids($productImagesIDs);
}
}

save the product to get WooCommerce Product ID

$product_id = $objProduct->save(); // it will save the product and return the generated product id

Note : For a Simple Product the above Steps are Enough, the below Steps are for Variable Product or Product having Attributes.

Below Code is Used to add Product Attributes.

$attributes = array(
array(“name”=>”Size”,”options”=>array(“S”,”L”,”XL”,”XXL”),”position”=>1,”visible”=>1,”variation”=>1),
array(“name”=>”Color”,”options”=>array(“Red”,”Blue”,”Black”,”White”),”position”=>2,”visible”=>1,”variation”=>1)
);
if($attributes){
$productAttributes=array();
foreach($attributes as $attribute){
$attr = wc_sanitize_taxonomy_name(stripslashes($attribute[“name”])); // remove any unwanted chars and return the valid string for taxonomy name
$attr = ‘pa_’.$attr; // woocommerce prepend pa_ to each attribute name
if($attribute[“options”]){
foreach($attribute[“options”] as $option){
wp_set_object_terms($product_id,$option,$attr,true); // save the possible option value for the attribute which will be used for variation later
}
}
$productAttributes[sanitize_title($attr)] = array(
‘name’ => sanitize_title($attr),
‘value’ => $attribute[“options”],
‘position’ => $attribute[“position”],
‘is_visible’ => $attribute[“visible”],
‘is_variation’ => $attribute[“variation”],
‘is_taxonomy’ => ‘1’
);
}
update_post_meta($product_id,’_product_attributes’,$productAttributes); // save the meta entry for product attributes
}

Below Code is Used to add Product Variants.

$variations = array(
array(“regular_price”=>10.11,”price”=>10.11,”sku”=>”ABC1”,”attributes”=>array(array(“name”=>”Size”,”option”=>”L”),array(“name”=>”Color”,”option”=>”Red”)),”manage_stock”=>1,”stock_quantity”=>10),
array(“regular_price”=>10.11,”price”=>10.11,”sku”=>”ABC2”,”attributes”=>array(array(“name”=>”Size”,”option”=>”XL”),array(“name”=>”Color”,”option”=>”Red”)),”manage_stock”=>1,”stock_quantity”=>10)

);
if($variations){
try{
foreach($variations as $variation){
$objVariation = new WC_Product_Variation();
$objVariation->set_price($variation[“price”]);
$objVariation->set_regular_price($variation[“regular_price”]);
$objVariation->set_parent_id($product_id);
if(isset($variation[“sku”]) && $variation[“sku”]){
$objVariation->set_sku($variation[“sku”]);
}
$objVariation->set_manage_stock($variation[“manage_stock”]);
$objVariation->set_stock_quantity($variation[“stock_quantity”]);
$objVariation->set_stock_status(‘instock’); // in stock or out of stock value
$var_attributes = array();
foreach($variation[“attributes”] as $vattribute){
$taxonomy = “pa_”.wc_sanitize_taxonomy_name(stripslashes($vattribute[“name”])); // name of variant attribute should be same as the name used for creating product attributes
$attr_val_slug = wc_sanitize_taxonomy_name(stripslashes($vattribute[“option”]));
$var_attributes[$taxonomy]=$attr_val_slug;
}
$objVariation->set_attributes($var_attributes);
$objVariation->save();
}
}
catch(Exception $e){
// handle exception here
}
}

Send Email with Attachment in PHP

<?php

// Settings
$name = "Name goes here";
$email = "xyz@gmail.com";
$to = "$name “;
$from = “info@xyz.com “;
$subject = “Here is your attachment”;
$mainMessage = “Hi, here’s the file.”;
$fileatt = “invoicepdf/INV_2056835173.pdf”; //file location
$fileatttype = “application/pdf”;
$fileattname = “INV_2056835173.pdf”; //name that you want to use to send or you can use the same name
$headers = “From: $from”;

// File
$file = fopen($fileatt, ‘rb’);
$data = fread($file, filesize($fileatt));
fclose($file);

// This attaches the file
$semi_rand = md5(time());
$mime_boundary = “==Multipart_Boundary_x{$semi_rand}x”;
$headers .= “\nMIME-Version: 1.0\n” .
“Content-Type: multipart/mixed;\n” .
” boundary=\”{$mime_boundary}\””;
$message = “This is a multi-part message in MIME format.\n\n” .
“–{$mime_boundary}\n” .
“Content-Type: text/plain; charset=\”iso-8859-1\n” .
“Content-Transfer-Encoding: 7bit\n\n” .
$mainMessage . “\n\n”;

$data = chunk_split(base64_encode($data));
$message .= “–{$mime_boundary}\n” .
“Content-Type: {$fileatttype};\n” .
” name=\”{$fileattname}\”\n” .
“Content-Disposition: attachment;\n” .
” filename=\”{$fileattname}\”\n” .
“Content-Transfer-Encoding: base64\n\n” .
$data . “\n\n” .
“–{$mime_boundary}–\n”;

// Send the email
if(mail($email, $subject, $message, $headers)) {

echo “The email was sent.”;

}
else {

echo “There was an error sending the mail.”;
}
?>

How to run laravel project on localhost

Hello friends… Today I am going to show how to run github laravel projects.

1. download the laravel project from github.

2. copy that project in hotdocs folder and open the folder location in cmd.

3. now first rename the “env.example file to.env”

4. you can configure the database information here.

5. now open cmd and run some commands…

-Run composer install or php composer.phar install

-Run php artisan key:generate

-Run php artisan migrate

-Run php artisan db:seed to run seeders, if any.

-Run php artisan serve

that’s all..