Sunday, February 10, 2019

phpMyPassion

Difference are DDL and DML?


DML


DML statements are SQL statements that manipulate data. DML stands for Data Manipulation Language. The SQL statements that are in the DML class are INSERT, UPDATE and DELETE. Some people also lump the SELECT statement in the DML classification.
DML example SQL statements are below -
  • SELECT – retrieve data from the a database
  • INSERT – insert data into a table
  • UPDATE – updates existing data within a table
  • DELETE – Delete all records from a database table
  • MERGE – UPSERT operation (insert or update)
  • CALL – call a PL/SQL or Java subprogram
  • EXPLAIN PLAN – interpretation of the data access path
  • LOCK TABLE – concurrency Control

DDL

Data Definition Languages (DDL) are used to define the database structure. Any CREATE, DROP and ALTER commands are examples of DDL SQL statements.
DDL example SQL commands are below -
  • CREATE – to create database and its objects like (table, index, views, store procedure, function and triggers)
  • ALTER – alters the structure of the existing database
  • DROP – delete objects from the database
  • TRUNCATE – remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT – add comments to the data dictionary
  • RENAME – rename an object
Read More

Friday, February 8, 2019

phpMyPassion

How To Integrate Facebook PHP SDK With Laravel 5.4


In this article I am explaining a simple process to setup Facebook Marketing SDK by PHP Artisan Command with laravel 5.4. You can get campaigns or your ad account data either setting up a cron using created command or running command on terminal.

First, edit composer.json in the project's root folder to include the Facebook SDK:


{    "require": {
        "facebook/php-business-sdk": "3.1.*"    }
}



Next run composer update at shell prompt to pull in the sdk to the vendor folder.

php composer.phar install --no-dev

If you do not have composer.phar in your Laravel project just copy that file to your project from Facebook Business SDK for PHP

Now we would like to use the Facebook SDK within our app as a command. But before doing that, let us setup our app_id, app_secret and default_graph_version which are parameters required while making requests to Facebook API. You can obtained app_id and app_secret from your Facebook App Settings.

Once we have these credentials from Facebook, we would now edit .env file in the project's root folder. Add them to the end:



FB_ADS_APP_ID="XXXXXXXXX"
FB_ADS_APP_SECRET="XXXXXXXXXXXXX"
FB_DEFAULT_GRAPH_VERSION=v3.2
FB_ACCESS_TOKEN="XXXXXXXXXXX"

Replace the xxx.. with the values provided to you. Note that the variable names are just my own creation. You can name them whatever you'd like. We would now have to use these variables to setup a separate config file. We need to do this so that we can use Laravel's config() helper function to retrieve the values wherever we want within the app. So let's create facebook-ads.php in the config folder and add the following:


return [
    'app_id' => env('FB_ADS_APP_ID', null),
    'app_secret' => env('FB_ADS_APP_SECRET', null),
    'default_graph_version' =>
env('FB_DEFAULT_GRAPH_VERSION', 'v2.8'),];
];



Now we have to create a class FacebookAdsService.php with below command..

php artisan make:console FacebookAdsService


<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class FacebookAdsService extends Command
{   
   /**
    * The name and signature of the console command.
    */
   protected $signature = 'facebook_sdk:service';
    /** 
     *The console command description.
     * @var string 
     */ 
   protected $description = 'Facebook ads api for campaign 
                            service, adset etc';    /** 
     * Create a new command instance.
     * @return void
     */    
   public function __construct(){
        parent::__construct();    
   }
   /** 
    * Execute the console command.
    * @return mixed 
    */    
   public function handle()    {
      //Your Code Goes Hare
    }
}


You have to write your all code to get facebook campaign & their reporting in the handle() function.

Now to run this command on our terminal we have to register it in Kernal.php with path "/app/Console/kernel.php".

So add "Command\FacebookAdsService::class" in the $commands array as below -



protected $commands = [    
   Commands\FacebookAdsService::class
];


Now we have all setup to get campaign or adset reporting from facebook marketing api.

Now just add some classes at the top of our FacebookAdsService class that we gonna use to get campaign data.


use FacebookAds\Object\AdAccount;
use FacebookAds\Api;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;


Now write your code to get facebook campaign data in its handle() function as below -

We have to instantiate Api object first to make an facebook api call.

To instantiate an Api object you will need a valid access token:


$app_id = env('FB_ADS_APP_ID');
$app_secret = env('FB_ADS_APP_SECRET');
$access_token =  env('FB_ACCESS_TOKEN');
Api::init($app_id, $app_secret, $access_token);
$api = Api::instance();


Get adAccount details from object -




$account_id = 'act_XXXXXXXX';
$account = new AdAccount($account_id);
$account->read();


Get All Campaigns -



$fields = array(  'name',  'objective',  'start_time',);
$params = array(  
      'effective_status' => array('ACTIVE','PAUSED'),
       );
$r = json_encode($account->getCampaigns(
     $fields,  
     $params
     )->getResponse()->getContent(), JSON_PRETTY_PRINT);


Get All AdSet -



$fields = array(  
  AdSetFields::ID,
  AdSetFields::NAME,
  AdSetFields::STATUS,
  AdSetFields::START_TIME,
  AdSetFields::END_TIME
); $r = json_encode($account->getAdSets( $fields )->getResponse()->getContent(), JSON_PRETTY_PRINT);



Get Ad Insight -


You can change fields and parameters according to your need.
Check All Ads Insights Parameters and Fields


$fields = array(  
     'adset_id',  
     'adset_name',  
     'impressions',  
     'clicks',  
     'ctr',  
     'spend');
$params = array(  
     'time_increment' => '1',  
     'date_preset' =>  'lifetime',  
     'breakdowns' => array( 
         'hourly_stats_aggregated_by_advertiser_time_zone',
     ),
     'sort' => array(
        'date_start_ascending'
      ),
);

$cmp_id = XXXXXXXXX;

$data = json_encode((new AdSet($cmp_id))->getInsights(
     $fields,
     $params
     )->getResponse()->getContent(), JSON_PRETTY_PRINT);


Run your command on terminal -

php artisan facebook_sdk:service

You can see your output on the terminal.

If you found any difficulty in setting up Facebook Sdk with laravel, you can intimate me by comment.  
Read More

Monday, February 4, 2019

phpMyPassion

Laravel Advanced how to pass variable into nested where function?

Whenever you want to use a variable inside the Closure scope, you need to use the "use" keyword to pass the variable into the Closure:


foreach ($user->locations as $location) {  
        $r = TableName::where('id', '<>', $this->id)    
            ->where(function ($q) use ($code) { // SEE HERE
                      $q->where('name', $code)        
                      ->orWhere('alias', $code); })
            ->get();
}



if you have an array variable like - $requestParam['name'] .

you have to define it before the query statement -


$name = $requestParam['name'];
$lastRecordResult = YrModel::where('type', self::table)
  ->where(function ($q) use ($name) {    
                $q->where('name', $name)      
                ->orWhere('alias', $name);  })  
  ->where('t_id', $requestParam['t_id'])  
  ->where('v_id', $requestParam['v_id'])  
  ->count();

Read More

Wednesday, December 26, 2018

phpMyPassion

Get A Insert Query Statement For All Rows in MySql

This is a common thing that usually required for back end programming.  Sometimes we need all rows of a table as an query statement just like -

INSERT INTO MyTable(ID,Col1,Col2,Col3) VALUES (100,'some vlaue','some value','2018-10-20');

So the question is "How do we get the insert query statement for this easily ?"

Here I am gonna write a simple PHP function by that you can get the insert query statement for all rows in a table :-

<?php
function makeInsertQuery($mysqli,$table, $where=null) {
    $sql="SELECT * FROM `{$table}`".(is_null($where) ? "" : " WHERE ".$where).";";
    $result=$mysqli->query($sql);

    $fields=array();
    foreach ($result->fetch_fields() as $key=>$value) {
        $fields[$key]="`{$value->name}`";
    }

    $values=array();
    while ($row=$result->fetch_row()) {
        $temp=array();
        foreach ($row as $key=>$value) {
            $temp[$key]=($value===null ? 'NULL' : "'".$mysqli->real_escape_string($value)."'");
        }
        $values[]="(".implode(",",$temp).")";
    }
    $num=$result->num_rows;
    return "INSERT `{$table}` (".implode(",",$fields).") VALUES \n".implode(",\n",$values).";";
}
?>


When you pass tableName to @makeInsertQuery($tableName) function. You will get below output..

INSERT INTO `tableName` (`id`, `parent_id`, `name`, `type`) VALUES
(1103, 1019, 'ios11.2.2', 'os'),
(1104, 1019, 'ios11.2.5', 'os'),
(1105, 1017, 'iosos_version', 'os'),
(1106, 1019, 'ios11.0.1', 'os'),
(1107, 1018, 'ios10.2.1', 'os'),
(1108, 1019, 'ios11.1.1', 'os'),
(1109, 1025, 'ios9.1', 'os'),
(1110, 1019, 'ios11.0.3', 'os'),
(1111, 1019, 'ios11.2.1', 'os'),
(1112, 1019, 'ios11.1.2', 'os'),
(1113, 1018, 'ios10.3.1', 'os'),
(1114, 1018, 'ios10.3.3', 'os'),
(1115, 1019, 'ios11.2.6', 'os'),
(1116, 1019, 'ios11.2', 'os'),
(1117, 1018, 'ios10.1.1', 'os');

So using above function you can get insert query statement for a table in MySql.

You can also get insert query statement by dumping or exporting the table into .sql file. So you can dump your table data with executing below command on terminal.

sudo mysqldump -u USERNAME -p DATABASE tableName > tableName.sql;

Windows users can export from MySql workbench:-


If you open the .sql file into editor, you will find query statement same as above. So just copy the all insert query statement and execute where you want.
Read More

Wednesday, December 19, 2018

phpMyPassion

MySQL Group By Day, Month Or Year

MySQL Group By Day, Month Or Year

Most frequently occurred problem that is faced by developers.  Here I am gonna explain you for the query Group by Day, Month or Year in MySQL.

Using the DATE_FORMAT operator, you can easily group the timestamp, date or datetime column using any format you want.

For example, I needed to group rows that were added on the same day. Here is my query:
select count(*), DATE_FORMAT(created_at,"%Y-%m-%d") as created_day FROM widgets GROUP BY DATE_FORMAT(created_at,"%Y-%m-%d")

This query will give you result like this :
count(*) | created_day
126 | 2012-04-12
168 | 2012-04-13
169 | 2012-04-14
189 | 2012-04-15
187 | 2012-04-16
131 | 2012-04-17

Similarly Group by month:

select count(*), DATE_FORMAT(created_at,"%Y-%m") as created_month FROM widgets GROUP BY DATE_FORMAT(created_at,"%Y-%m")

Similarly Group by year:

select count(*), DATE_FORMAT(created_at,"%Y") as created_year FROM widgets GROUP BY DATE_FORMAT(created_at,"%Y")



Read More

Friday, November 30, 2018

phpMyPassion

How To Setup Cron Job on AWS

Cron job is a process to run a page automatically in background without interrupting user. You can execute a page automatically at any time on daily basis by setting up a cron job.


How To Setup Cron Job on AWS

       I have already explained about setting up a cron job on godaddy server in one of my article. So now here I am going to explain a step by step process for setting up cron job in AWS too for ubuntu users.
Process to Setting Up AWS Cron:-
Step #1. Login to your AWS instance through Terminal by using your server credentials.
Step #2. Type crontab -e.
Step #3. Now editor will open inside your terminal that will look like below..

How To Setup Cron Job on AWS

Step #4.  You have to add your script command inside it as below.

* * * * * php /var/www/html/myscript.php
Here 5 star shows -

1st * is for minute (0-59)
2nd * is for hour (0-23)
3rd * is for day (1-31)
4th * is for month (1-12)
5th * is for day-of-week (0-7[where both 0 and 7 mean Sun, 1 = Mon, 2 = Tue, etc])

After setting cron time in min, hour, day, month, day-of-week we set our file path which we want to execute automatically according to date & time.

You can edit cron by pressing Insert key from keyboard and to paste your command inside editor you have to press ctrl+shift+v.
Now press esc and after that type :wq to save and exit from editor.
Step #5. Now check your cron is save successfully or not by typing crontab -l in terminal.
Step #6. Make sure you change your file permission executing command chmod 755 /var/www/html/myscript.php in terminal. 
myscript.php

<?php
$fr_email = '[email protected]';
$subj = 'Hi this is from AWS Cron';
/* Create a simple msg body */
$body = "Welcome to myscript\n";
$body .= "\n";
// Now send email
mail($to,  $subj, $body, "From: <$fr_email>");
?>

You will get an email every time when your cron will run as per your above php script.

More About Cron Job:

Read More

Saturday, October 27, 2018

phpMyPassion

Top PHP7 Interview Questions And Answers for Freshers & Experienced

This article shows up top frequently asked PHP7 interview questions and answers for PHP Developers, This list of PHP interview questions and answers will be helpful for PHP programmers.


Top PHP7 Interview Questions And Answers for Freshers & Experienced


Question #1 - How array_walk function works in PHP?


It is used to update the elements/index of original array.
How: in array_walk, two parameter are required. 
  1. original array
  2. An callback function, with use of we update the array. 
Question #2 - How to achieve Multilevel inheritance in PHP7?


//base class
class a{}

//parent class extend the base class
class bextends a{}

//chid class extend the parent class
class c extends b{}

Question #3 - How to get 2nd highest salary of employee, if two employee may have same salary?


select salary from employee group by salary order by salary limit 1,1

Question #4 - require_once(), require(), include().What is difference between them?


require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
Question #5 - What type of inheritance supports by PHP7?


There are following type of inheritance 

  • Single Inheritance - Support by PHP
  • Multiple Inheritance - Not support
  • Hierarchical Inheritance - Support by PHP
  • Multilevel Inheritance - Support by PHP
Question #6 - How do you call a constructor for a parent class?

parent::constructor($value);
Question #7 - How to find duplicate email records in users table?

SELECT u1.first_name, u1.last_name, u1.email FROM users as u1
INNER JOIN (
    SELECT email FROM users GROUP BY email HAVING count(id) > 1
    ) u2 ON u1.email = u2.email;

Question #8- What is the difference between Session and Cookie?
Both are used to store user information on server. The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user's computers in the text file format. Cookies can't hold multiple variable while session can hold multiple variables..We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
Question #9- How to pass data in header while using CURL?
$url='http://www.web-technology-experts-notes.in';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'headerKey: HeaderValue ',
  'Content-Type: application/json',
  "HTTP_X_FORWARDED_FOR: xxx.xxx.x.xx"
));
echo curl_exec($ch);
curl_close($ch);

Question #10 - What is Final Keyword in PHP7?

PHP7 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final keyword.
Question #11 - How can we prevent SQL-injection in PHP?


Sanitize the user data before Storing in database.
While displaying the data in browser Convert all applicable characters to HTML entities using htmlentities functions.
Question #12 - How to set header in CURL?

curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); 

Question #13 - What are different type of sorting functions in PHP7?

sort() - sort arrays in ascending order. 
asort() - sort associative arrays in ascending order, according to the value.
ksort() - sort associative arrays in ascending order, according to the key.
arsort() - sort associative arrays in descending order, according to the value.
rsort() - sort arrays in descending order.
krsort() - sort associative arrays in descending order, according to the key.
array_multisort() - sort the multi dimension array.
usort()- Sort the array using user defined function.

Question #14 - How to redirect https to http URL and vice versa in .htaccess?

Redirect https to http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Redirect http to https


RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Question #15 - What are benefits of .htaccess?

  • Routing the URL
  • Mange Error Pages for Better SEO
  • Redirection pages
  • Detect OS (like Mobile/Laptop/Ios/Android etc)
  • Set PHP Config variable
  • Set Environment variable
  • Allow/Deny visitors by IP Address
  • Password protection for File/Directory
  • Optimize Performance of website
  • Improve Site Security 

Question #16 - How we can retrieve the data in the result set of MySQL using PHP7?


  • mysqli_fetch_row()
  • mysqli_fetch_array()
  • mysqli_fetch_object()
  • mysqli_fetch_assoc()

Question #17 - What is the use of explode() function ?


This function is used to split a string into an array. Syntax : array explode( string $delimiter , string $string [, int $limit ] ); 
Question #18 - What is the difference between explode() and split() functions?


Split function splits string into array by regular expression. Explode splits a string into array by string.
Both function are used to breaks a string into an array, the difference is that Split() function breaks split string into an array by regular expression and explode() splits a string into an array by string. explode() is faster than split() because it does not match the string based on regular expression.  
Question #19 - What is the use of mysqli_real_escape_string() function?


mysqli_real_escape_string() function mainly used to escapes special characters in a string for use in an SQL statement
Question #20 - Write down the code for save an uploaded file in php.


if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
Question #21 - How to create a text file in php7?


$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" ); exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
Question #22 - How to strip whitespace (or other characters) from the beginning and end of a string ?


We can use trim() function to remove whitespaces or other predefined characters from both sides of a string.
Question #23 - What is output of following?
$a = '10';
$b = &$a;

$b = "2$b";

echo $a;
echo $b;

Output


210
210

Question #24 - What are Traits?


Traits are a mechanism that allows you to create reusable code in PHP7 where multiple inheritance is not supported. To create a Traits we use keyword trait

Example of Traits
trait users {
    function getUserType() { }
    function getUserDescription() {  }
    function getUserDelete() {  }
}

class ezcReflectionMethod extends ReflectionMethod {
    use users;    
}

class ezcReflectionFunction extends ReflectionFunction {
    use users;
}

Question #25 - How to extend a class defined with Final?


No, You can't extend. A class declare with final keyword can't be extend.
Question #26 - What is full form of PSRs?

PHP Standards Recommendations. 
Question #27 - How do you execute a PHP script from the command line?


  • Get the php.exe path from server (My PHP path is : D:\wamp\bin\php\php5.5.12)
  • In environment variable, Add this path path under PATH variable.
  • Re-start the computer.
  • Now, you can execute php files from command file.
php index.php

Question #28 - What is stdClass in PHP7?


It is PHP7 generic empty class.
stdClass is used to create the new Object. For Example
$newObj = new stdClass();
$newObj->name='What is your name?';
$newObj->description='Tell me about yourself?';
$newObj->areYouInIndia=1;
print_r($newObj);

Output


stdClass Object
(
    [name] => What is your name?
    [description] => Tell me about yourself?
    [areYouInIndia] => 1
)

Question #29 - How to start displaying errors in PHP7 application ?

Add following code in PHP.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

OR
Add following code in .htacess


php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on

Question #30 - What are different type of errors?


E_ERROR: A fatal error that causes script termination.
E_WARNING: Run-time warning that does not cause script termination.
E_PARSE: Compile time parse error.
E_NOTICE: Run time notice caused due to error in code.
E_CORE_ERROR: Fatal errors that occur during PHP's initial startup.
E_CORE_WARNING: Warnings that occur during PHP's initial startup.
E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
E_USER_ERROR: User-generated error message.
E_USER_WARNING: User-generated warning message.
E_USER_NOTICE: User-generated notice message.
E_STRICT: Run-time notices.
E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error 
E_ALL: Catches all errors and warnings 

Question #31 - When to use self over $this?

Use $this to refer to the current object.
Use self to refer to the current class.

Example of use of $this


class MyClass1 {
    private $nonStaticMember = 'nonStaticMember  member Called.';        
    
    public function funcName() {
        return $this->nonStaticMember;
    }
}

$classObj = new MyClass1();
echo $classObj->funcName();//nonStaticMember  member Called.


Example of use of SELF


class MyClass2 {
    private static $staticMember = 'staticMember  member Called.';        
    
    public function funcName() {
        return self::$staticMember;
    }
}

$classObj = new MyClass2();
echo $classObj->funcName(); //staticMember  member Called.

Read More