Nov 11, 2014

AngularJS For One Page Application With PHP MYSQL (Insert Data In DB)

AngularJS is a JavaScript framework having only JavaScript code. It is the best framework for those who want to make one page application. Like Voting Web Application, Lucky draw contestant etc. AngularJS extends the HTML tags properties with the ng-directives.

AngularJS is most optimized and easy framework for client side web page. Below is the google AngularJS API URL to use in our web pages.

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Note: 1. Always use updated version of angular.min.js Google API.
Note: 2. Use data-ng- instead of ng- for HTML5 valid page.

Here, I will show some basic example of AngularJS with PHP code of my understanding, for more detail visit official website https://angularjs.org/

Following are the some important ng-directives we should know.

ng-app:  AngularJS application initialization. It is compulsory to declare scope of application. We can create multiple ng-app within a page. Example: <body ng-app="ngAppName"></body> OR <div ng-app="ngAppName"></div> OR <div ng-app="ngAppName2"></div><div ng-app="ngAppName3"></div>

ng-bind: This is same as innerHTML of html. We can assign value of any input field to html tags. Example: <p ng-bind="field name"></p> OR Use AngularJS expressions same as ng-bind. Example: <p>Addition: {{ 15 + 15 }}</p> OR <p>Name: {{ field name }}</p>

ng-init: This directive use to initialize the AngularJS application variables. Example: <div ng-app="ngAppName" ng-init="fname='pranaydac08'">

ng-model: It is pointed to the input field variable name which bind variable to this ng model.

ng-controller: AngularJS applications are manage by controllers. We can write multiple controllers in a ng-app. Example: <div ng-app="ngAppName" ng-controller="myController">

ng-repeat: This is use for repeatation of an HTML element like foreach(namesObject as fname). Example: <li ng-repeat="fname in namesObject">{{ fname }} </li>


AngularJS Example With PHP MYSQL (Insert Data In DB):

Step 1: Create DB & Table as below

CREATE DATABASE angularJS; 
CREATE TABLE users( `id` INT(11) NOT NULL AUTO_INCREMENT, `username` VARCHAR(250), `email` VARCHAR(250), PRIMARY KEY (`id`) );

Step 2: Create index.php file and copy below code there.

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
    
<body ng-app="myApp">
<h2>AngularJS Example</h2>

<form ng-controller="myCotrollerName" name="myForm" novalidate>

<p ng-repeat="error in errors">* {{ error}} </p>   
<p ng-repeat="msg in msgs">* {{ msg}} </p>
  
<p>Username:<br>
<input type="text" name="username" ng-model="username" required placeholder="User Name">
<span style="color:red" ng-show="myForm.username.$dirty && myForm.username.$invalid">
<span ng-show="myForm.username.$error.required">Username is required.</span>
</span>
</p>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required placeholder="Email">
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>

<p>
<!--<input type="button" ng-click='SignUp();' ng-disabled="myForm.username.$dirty && myForm.username.$invalid ||  myForm.email.$dirty && myForm.email.$invalid" value="Submit"/>-->
<button ng-click='SignUp();'>Submit</button>
</p>

</form>

<script>
var myApp = angular.module("myApp", []); 
myApp.controller("myCotrollerName", function($scope, $http) {
    $scope.username = 'pranaydac08';
    $scope.email = 'pranaydac.test@gmail.com';
$scope.errors = [];
$scope.msgs = [];

$scope.SignUp = function() {

$scope.errors.splice(0, $scope.errors.length); // blank all error messages
$scope.msgs.splice(0, $scope.msgs.length);// blank all messages

// http post call to save_info.php file to save data in db
$http.post('save_info.php', {'username': $scope.username, 'email': $scope.email}
).success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { 
$scope.errors.push(status);
});
}
}); 

</script>


</body>
</html>


Step 3: Create save_info.php file and copy below code there. This code will save data into database.

<?php
//Get the data from http request 
$data = json_decode(file_get_contents("php://input"));
$username = mysql_real_escape_string($data->username); // Use mysql_real_escape_string to prevent data from sql injection.
$email = mysql_real_escape_string($data->email);
 
/* DB Connection @ localhost  */
$db_hostname = 'localhost';
$db_userName = 'root';
$db_password = '';
$db_name = 'angularJS';

$con = mysql_connect($db_hostname, $db_userName, $db_password);
mysql_select_db($db_name, $con);
 
$query = 'select count(*) as cnt from users where email ="' . $email . '"';
$query_res = mysql_query($query);
$res = mysql_fetch_assoc($query_res);
 
if ($res['cnt'] == 0) {
$query_ins = 'INSERT INTO users (username,email) values ("' . $username . '","' . $email . '")';
$query_ins_res = mysql_query($query_ins);
if ($query_ins_res) {
$arr = array('msg' => "User Added Successfully!!!", 'error' => '');
$jsn_data = json_encode($arr);
print_r($jsn_data);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting user data');
$jsn_data = json_encode($arr);
print_r($jsn_data);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists!');
$jsn_data = json_encode($arr);
print_r($jsn_data);
}
?>

Step 4: Done. Please comments, if having any issue.

Aug 20, 2014

Apply Online for 308 Technician Gr-III Posts ( For ITI ) in MAHAGENCO Recruitment 2014

Apply Online for 308 Technician Gr-III Posts ( For ITI - Electrician, Fitter, Electronics, Electronics Mechanics etc.) in MAHAGENCO Recruitment 2014

Click below to Apply.....
http://ibps.sifyitest.com/mahagenx14bs/

Last Date: 10-Sep-2014

More Detail... : http://www.mahagenco.in/index.php/2012-07-20-02-24-48

Jul 30, 2014

What is Magento's skeleton and architecture

Magento is one of the most powerful E-Commerce PHP framework. Magento is very user friedly and easy to manage products, categories and sales orders etc. by administrator but vice versa for newbie developers, if you are just came in the wolrd of Magento and you are new born PHP developer then you will going to face lot of the problems to understand the Magento and it's architecture. It is like when you got the admission in 1st standard and learning Alphbets and Numbers... But what if someone makes all those things to learn and understand easily then no one can stop us to achive our target.

Don't worry guys... We have someone to help us.

You can visit my friend's blog to understand the Magento architecture easily. Click on below link.

http://kamleshkamble.blogspot.in/2014/05/magento-design-patterns.html

Jul 29, 2014

How to integrate FirePHP console logger in PHP

FirePHP is the Console Message Logger useful for ajax functionality to debug error and warning or information in browser console. This is the one of the most useful tool for the PHP developer to debug the issue or functionality. My friend Rajesh did this job for us very beautifully and with easy steps.

You can see how to install FirePHP by visiting my friend's blog below.

http://rajeshganjeer.wordpress.com/2014/07/18/firephp-the-console-message-logger-useful-for-ajax/

Thanks to Rajesh Ganjir for useful information shared.  

Jul 23, 2014

How to write, read and delete text file on Amazon S3 Buckets using zend framework

Write sample.txt File:

 
      
require_once "./library/Zend/Service/Amazon/S3.php";



$s3 = new Zend_Service_Amazon_S3($awsKey, $awsSecret);



$perms = array(

 Zend_Service_Amazon_S3::S3_ACL_HEADER =>

  Zend_Service_Amazon_S3::S3_ACL_PUBLIC_READ

);

try

{

 //writing content to sample.txt file

 $ret = $s3->putObject(

  $bucketName . '/sample.txt',

  'Sample text content',

  $perms

 );

}

catch (Exception $e)

{

 echo $e->getMessage();          

} 

Read sample.txt file data from s3 bucket:

 
      
try

{ //read txt_content from txt file      

 $txt_content = $s3->getObject($bucketName . '/sample.txt');    

}

catch (Exception $e)

{

 echo $e->getMessage();

}

Delete text file:


try

{

 $ret = $s3->removeObject($bucketName. "/sample.txt");

}

catch (Exception $e)

{

 echo $e->getMessage();

}

Jul 9, 2014

How to create admin Custom System Configuration Textarea field with wysiwyg editor enabled in Magento

We are going to create a custom module for above functionality, follows the below steps one by one.

Declaration: 
Namespace Name: Pg
Module Name: Adminconfigeditor

Step1: Create Pg_Adminconfigeditor.xml file and add in below path: app\etc\modules

 
      
<?xml version="1.0"?>

<config>

    <modules>

        <Pg_Adminconfigeditor>

            <active>true</active>

            <codePool>local</codePool>

        </Pg_Adminconfigeditor>

    </modules>

</config>


      

 


Step2: Create IndexController.php file and add in below path: app\code\local\Pg\Adminconfigeditor\controllers

 
      
<?php



class Pg_Adminconfigeditor_IndexController extends Mage_Core_Controller_Front_Action {



    public function indexAction() {

  

    }



}


      

 


Step3: Create Editor.php file and add in below path: app\code\local\Pg\Adminconfigeditor\Block\Adminhtml\System\Config\Editor.php

 
      
<?php

 class Pg_Adminconfigeditor_Block_Adminhtml_System_Config_Editor

    extends Mage_Adminhtml_Block_System_Config_Form_Field

    implements Varien_Data_Form_Element_Renderer_Interface {



 protected function _prepareLayout() {

   parent::_prepareLayout();

   if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {

    $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);

   }

 }

    protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) {

        $element->setWysiwyg(true);

        $element->setConfig(Mage::getSingleton('cms/wysiwyg_config')->getConfig());

        return parent::_getElementHtml($element);

    }

}


      

 


Step4: Create Data.php file and add in below path: app\code\local\Pg\Adminconfigeditor\Helper\Data.php

 
      
<?php

class Pg_Adminconfigeditor_Helper_Data extends Mage_Core_Helper_Abstract

{

}

      

 


Step5: Create config.xml file and add in below path: app\code\local\Pg\Adminconfigeditor\etc\config.xml

 
      
<?xml version="1.0"?>

<config>

    <modules>

        <Pg_Adminconfigeditor>

            <version>0.1.0</version>

        </Pg_Adminconfigeditor>

    </modules>

    <frontend>  

        <routers>

            <adminconfigeditor>

                <use>standard</use>

                <args>

                    <module>Pg_Adminconfigeditor</module>

                    <frontName>adminconfigeditor</frontName>

                </args>

            </adminconfigeditor>

        </routers>       

    </frontend>

    <global>               

        <blocks>

            <adminconfigeditor>

                <class>Pg_Adminconfigeditor_Block</class>

            </adminconfigeditor>

        </blocks>

        <helpers>

            <adminconfigeditor>

                <class>Pg_Adminconfigeditor_Helper</class>

            </adminconfigeditor>         

        </helpers>           

    </global>

 <adminhtml>

  <acl>

   <resources>

    <all>

     <title>Allow Everything</title>

    </all>

    <admin>

     <children>

      <system>

       <children>

        <config>

         <children>

          <pg_section>

           <title>PG - All</title>

          </pg_section>

         </children>

        </config>

       </children>

      </system>

     </children>

    </admin>

   </resources>

  </acl>

 </adminhtml>   

</config>

      

 


Step6: Create system.xml file and add in below path: app\code\local\Pg\Adminconfigeditor\etc\system.xml

 
      
<?xml version="1.0" encoding="UTF-8"?>

<config>

    <tabs>

        <pg translate="label" module="adminconfigeditor">

            <label>Pg Admin Config Editor</label>

            <sort_order>100</sort_order>

        </pg>

    </tabs>

    <sections>

        <pg_section translate="label" module="adminconfigeditor">

            <label>Extension Options</label>

            <tab>pg</tab>

            <sort_order>1000</sort_order>

            <show_in_default>1</show_in_default>

            <show_in_website>1</show_in_website>

            <show_in_store>1</show_in_store>

            <groups>

                <pg_group translate="label" module="adminconfigeditor">

                    <label>My Extension Options</label>

                    <frontend_type>text</frontend_type>

                    <sort_order>1000</sort_order>

                    <show_in_default>1</show_in_default>

                    <show_in_website>1</show_in_website>

                    <show_in_store>1</show_in_store>

                    <fields>

                        <pg_input translate="label">

                            <label>My Input Field: </label>

                            <comment>My Comment</comment>

                            <frontend_type>text</frontend_type>

                            <sort_order>20</sort_order>

                            <show_in_default>1</show_in_default>

                            <show_in_website>1</show_in_website>

                            <show_in_store>1</show_in_store>

                        </pg_input>

                        <pg_select translate="label">

                            <label>My Dropdown: </label>

                            <comment>Test Comment</comment>

                            <frontend_type>select</frontend_type>

                            <sort_order>90</sort_order>

                            <show_in_default>1</show_in_default>

                            <show_in_website>1</show_in_website>

                            <show_in_store>1</show_in_store>

                            <source_model>adminhtml/system_config_source_yesno</source_model>

                        </pg_select>

      <pg_textarea_wysiwyg>

          <label>Wysiwyg Textarea Example</label>

          <frontend_type>editor</frontend_type>

          <frontend_model>adminconfigeditor/adminhtml_system_config_editor</frontend_model>

          <sort_order>120</sort_order>

          <show_in_default>1</show_in_default>

          <show_in_website>1</show_in_website>

          <show_in_store>1</show_in_store>

          <comment>Textarea field with wysiwyg editor enabled.</comment>

      </pg_textarea_wysiwyg>

                    </fields>

                </pg_group>

            </groups>

        </pg_section>

    </sections>

</config>


      

 


Step7: Done. Go to admin system configuration, you should see the below screen. Note: Clear cache and make sure you have enabled wysiwyg setting from admin -> system->config->content management.

Jun 16, 2014

How to add custom new or update or delete category attribute in Magento using SQL setup

1. How to add new category attribute:

 
      
    <?php

    /** @var $this Mage_Eav_Model_Entity_Setup */

    $this->startSetup();



    /** Add new atribute */

    $this->addAttribute('catalog_category', 'ur_custom_attribute_name', array(

     'group'         => 'General Information',

     'input'         => 'textarea',

     'type'          => 'text',

     'label'         => 'ur custom attribute title',

     'backend'       => '',

     'visible'       => 1,

     'required'      => 0,

     'user_defined'     => 1,   

     'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,

    ));



    $this->endSetup();



    ?>

      

 


2. How to remove category attribute:
                   
<?php

    /** @var $this Mage_Eav_Model_Entity_Setup */

    $this->startSetup();



    /** Remove existing atribute */

    $this->removeAttribute('catalog_category', 'ur_custom_attribute_name');



    $this->endSetup();



    ?>



      

 


3. How to update category attribute:
                 
 <?php

     /** @var $this Mage_Eav_Model_Entity_Setup */

     $this->startSetup();



     /** Update existing atribute */

     $categoryEntityTypeId = $this->getEntityTypeId('catalog_category');

     $this->updateAttribute($categoryEntityTypeId, 'ur_custom_attribute_name', 'is_wysiwyg_enabled', 1);

     $this->updateAttribute($categoryEntityTypeId, 'ur_custom_attribute_name', 'is_html_allowed_on_front', 1);



     $this->endSetup();



     ?>


      

 


Note: Please add '<class>Mage_Catalog_Model_Resource_Setup</class>' in config.xml 

           
       Path: <resources>

      <affiliatetrack_setup>

       <setup>

        <module>Urnameapce_Urmodulename</module>

        <class>Mage_Catalog_Model_Resource_Setup</class>

      



 


Ignore it, if already done.
Assumption: You have created your custom module.

Jun 12, 2014

Object Oriented Programming in Javascript

Object Oriented Programming concept in Javascript is very similar to other object oriented programming language concept for example : C++, JAVA, C#, Python, PHP, Ruby and Objective-C

This is not the Rocket Science, it very simple if you already have the knowledge of OOPS in any programming language.

Ok. Lets start with the introduction of Object Oriented Javascript.

Introduction 
JavaScript has several objects included in its core; for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.

       

           Example: alert(Math.random());


       
 

Every object in JavaScript is an instance of the object Object and therefore inherits all its properties and methods.

Javascript Class:
JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person


       

          Example: function Person() { }

       
 

Javascript Object (Class Instance):
To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later.

In the example below we define a class named Person and we create two instances (person1 and person2).
Example:
       

          function Person() { }

var person1 = new Person();

var person2 = new Person();


       
 

Javascript Property (object attribute):
Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the prototype property of the class (function) so that inheritance works correctly.

Working with properties from within the class is done by the keyword this, which refers to the current object. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property; this is the same syntax used by C++, Java, and a number of other languages. (Inside the class the syntax this.Property is used to get or set the property's value.)

In the example below we define the gender property for the Person class and we define it at instantiation.

       

function Person(gender) {

  this.gender = gender;

  alert('Person instantiated');

}



var person1 = new Person('Male');

var person2 = new Person('Female');



//display the person1 gender

alert('person1 is a ' + person1.gender); // person1 is a Male


       
 

This is just a sample of Object Oriented Javascript Programming, Please read below article for details.

Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

http://www.functionx.com/javascript/Lesson07.htm

Jun 4, 2014

How to create virtual host for phpmyadmin to access database in Ubuntu (LAMP)

Step 1 — Create the Directory Structure:
- Create a folder name as "phpmyadmin" in /var/www directory.
sudo mkdir -p /var/www/phpmyadmin

Step 2 — Grant Permissions:
sudo chown -R $USER:$USER /var/www/phpmyadmin
sudo chmod -R 755 /var/www

Step 3 — Create New Virtual Host Files
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/phpmyadmin.conf
Now Open the new file as follow
sudo gedit /etc/apache2/sites-available/phpmyadmin.conf

Copy the code below and replace with all old text inside this file.
<VirtualHost *:8080>
    ServerAdmin admin@test.phpmyadmin
    ServerName phpmyadmin
    ServerAlias www.phpmyadmin
    DocumentRoot /usr/share/phpmyadmin/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Save and close the file.

Step 4 — Link our virtual host with localhost in /etc/hosts file:
Open file hosts as follow
sudo gedit /etc/hosts
Add the below line in host file
127.0.1.1 phpmyadmin
Save and close the file.

Step 5 — Enable the New Virtual Host Files
We can use the a2ensite tool to enable each of our sites like this:
sudo a2ensite phpmyadmin.conf

// Reload the apache configuration
  sudo service apache2 reload

  // Restart Apache
  sudo service apache2 restart

Step 6 — Test your phpmyadmin site
http://phpmyadmin

Finished!!!!!!!

Jun 3, 2014

How To Create Virtual Host on Ubuntu OS (LAMP)

## Note:: Assuming you have installed LAMP ##

Case: We want to create a virtual host name as "test.localhost"

Step 1 — Create the Directory Structure:
- Create a folder name as "test.localhost" in /var/www directory.
sudo mkdir -p /var/www/test.localhost

Step 2 — Grant Permissions:
sudo chown -R $USER:$USER /var/www/test.localhost
sudo chmod -R 755 /var/www

Step 3 — Create Demo Page for Virtual Host
- Create index.php file inside the folder /var/www/test.localhost
and write below sample text in index.php file and save.
<?php
echo 'Virtual host testing succesfullly done...';
?> 

Step 4 — Create New Virtual Host Files
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/test.localhost.conf
Now Open the new file as follow
sudo gedit /etc/apache2/sites-available/test.localhost.conf

Copy the code below and replace with all old text inside this file

<VirtualHost *:80>
    ServerAdmin admin@test.localhost
    ServerName test.localhost
    ServerAlias www.test.localhost
    DocumentRoot /var/www/test.localhost
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Save and close the file.

Step 5 — Link our virtual host with localhost in /etc/hosts file:
Open file hosts as follow
sudo gedit /etc/hosts
Add the below line in host file
127.0.1.1 test.localhost
Save and close the file.

Step 6 — Enable the New Virtual Host Files
We can use the a2ensite tool to enable each of our sites like this:
sudo a2ensite test.localhost.conf

When you are finished, you need to restart Apache to make these changes take affect:
sudo service apache2 restart

Step 7 — Test your site
http://test.localhost

You should see a page that looks like this:
Virtual host testing succesfullly done...

Finished!!!!!!!

Jan 23, 2014

How to update Sugar CRM user Account & contacts detail usign SUGAR API in PHP?

$set_entry_parameters = array(
//session id
"session" => $session_id,
//The name of the module from which to retrieve records.
"module_name" => "Accounts",
//Record attributes
"name_value_list" => array(
 //to update a record, you will need to pass in a record id which you have stored in DB
 array("name" => "id", "value" => $accountStoredId),
 array("name" => "name", "value" => $name),  
 array('name'=>'billing_address_street ', "value"=>$billing_address_street),
 array('name'=>'billing_address_city', "value"=>$billing_address_city),
 array('name'=>'billing_address_state ', "value"=>$billing_address_state),
 array('name'=>'billing_address_postalcode ', "value"=>$billing_address_postalcode)
),
);
$set_entry_result = call("set_entry", $set_entry_parameters, $url);

Related Post:
How to use Sugar CRM API integration with PHP?
How to add user data in Sugar CRM custom module and make relationship in PHP?

How to add user data in Sugar CRM custom module and make relationship in PHP?

Step 1: Please follow the same steps as shown in this article... How to use Sugar CRM API integration with PHP?

Step 2: But please note the following points for custom module.

Note 1: Custom module name must be like 'CustomModulePackagekey_ModuleName'.
Note 2: 'link_field_name' must be the Related Module Name
These above details you can find in 'ModuleBuilder' section of Sugar Admin account.

Step 3: Done. :)

How to integrate Sugar CRM API with PHP?

Step 1: Login connection with SUGAR

$url = "https://urdomain.sugarondemand.com/service/v4_1/rest.php"; //Rest api url
$username = "urusername"; // sugar account username
$password = "urpassword"; // sugar account password

//login Authentication Process
$login_parameters = array(
"user_auth" => array(
 "user_name" => $username,
 "password" => md5($password),
 "version" => "1"
),
"application_name" => "URWebsiteName",
"name_value_list" => array(),
);
//call to sugar api
$login_result = call("login", $login_parameters, $url);
//get session id
$session_id = $login_result->id;

Step 2: Create call() function as follows

function call($method, $parameters, $url)
{
ob_start();
$curl_request = curl_init();

curl_setopt($curl_request, CURLOPT_URL, $url);
curl_setopt($curl_request, CURLOPT_POST, 1);
curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($curl_request, CURLOPT_HEADER, 1);
curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);

$jsonEncodedData = json_encode($parameters);

$post = array(
"method" => $method,
"input_type" => "JSON",
"response_type" => "JSON",
"rest_data" => $jsonEncodedData
);

curl_setopt($curl_request, CURLOPT_POSTFIELDS, $post);
$result = curl_exec($curl_request);
curl_close($curl_request);

$result = explode("\r\n\r\n", $result, 2);
$response = json_decode($result[1]);
ob_end_flush();

return $response;
}

Step 3: How to add user data in 'Accounts' Module.

$set_entry_parameters = array(
//session id
"session" => $session_id,
//The name of the module from which to retrieve records.
"module_name" => "Accounts",
//Record attributes
"name_value_list" => array(  
 array("name" => "name", "value" => $name),  
 array('name'=>'billing_address_street ', "value"=>$billing_address_street),
 array('name'=>'billing_address_city', "value"=>$billing_address_city),
 array('name'=>'billing_address_state ', "value"=>$billing_address_state),
 array('name'=>'billing_address_postalcode ', "value"=>$billing_address_postalcode)
),
);
$set_entry_result = call("set_entry", $set_entry_parameters, $url);
$accountId = $set_entry_result->id; // Store $accountId in db for update the same record in future

Step 4: How to add user data in 'Contacts' Module.

$set_entry_parameters_contacts = array(
 
"session" => $session_id,
"module_name" => "Contacts",

"name_value_list" => array(  

array("name" => 'first_name', "value" => $first_name),
array("name" => 'last_name', "value" => $last_name),
array('name'=>'account_name', "value"=>$account_name),
array('name'=>'middle_name_c', "value"=>$middle_name_c), // middle_name_c is the custom field in Contacts module
array('name'=>'email1', "value"=>$email1)

),
);
}

$set_entry_result_contact= call("set_entry", $set_entry_parameters_contacts, $url);
$contactId = $set_entry_result_contact->id; // Store $accountId in db for update the same record in future

Step 5: Now let's make relationship between Accounts & Contacts modules

if($accountId != "" && $contactId != "")
{
$parameters = array( 
'session' => $session_id,
'module_name' => 'Accounts',
'module_id' => $accountId,
'link_field_name' => 'contacts', 
'related_ids' => array($contactId) 
); 

$relationship_res = call('set_relationship', $parameters, $url);
}

Step 6: Done. :)

How to add user data in Sugar CRM custom module and make relationship in PHP?