+ Reply to Thread
Page 1 of 3 1 2 3 LastLast
Results 1 to 10 of 23

Thread: Salesforce MySQL Full Replication Script Process

  1. #1
    mike's Avatar
    mike is offline Administrator
    Join Date
    May 2007
    Location
    Wylie, Texas
    Posts
    557
    Blog Entries
    15

    Salesforce MySQL Full Replication Script Process

    One item while browsing my own site that noticed is that some of the tutorials or examples are really not all that clear and for that I apologize.

    A developer new to Salesforce wanted me to help them out with a replication script that would download/replicate data to Salesforce. I agreed to help him out and I wanted to share this with everyone to give them an idea how really simple it is to create this.

    So I am going to release an entire script that will work with any object in Salesforce, just simply by changing the query to Salesforce and the table you want to update in MySQL.

    Step 1:

    Go to My MySQL Schema generator and create a your own organization's MySQL schema. This covers objects from A to Z, including custom objects.

    1. Once you fill out all the pertinent information, it will log in to Salesforce
    2. Create your schema and generate a download
    3. All data and log in information is not stored and the file is deleted once the download is complete.

    or simply create your own MySQL schema from scratch.

    Here is the schema from my schema generator for the Product2 object from my development instance:

    Code:
    CREATE TABLE sforce_product2(
            Id VARCHAR(18),
            Name VARCHAR(255),
            ProductCode VARCHAR(255),
            Description TEXT,
            IsActive VARCHAR(5),
            CreatedDate DATETIME,
            CreatedById VARCHAR(18),
            LastModifiedDate DATETIME,
            LastModifiedById VARCHAR(18),
            SystemModstamp DATETIME,
            Family VARCHAR(40),
            IsDeleted VARCHAR(5),
            PRICE_PER_1K__c INT(0),
            PRICE_PER_5K__c INT(0)
        );
    I wrote a script that creates bogus records in Salesforce, 156,000 of them. to test the MySQL replication


    STEP 2:

    Here is the entire script that will replicate any object to MySQL just by simply changing a couple of lines and the SOQL query to salesforce

    PHP Code:
    <?php
    ini_set
    ("soap.wsdl_cache_enabled","0");


    require_once (
    './includes/soapclient/SforcePartnerClient.php');

    /***************************************************************************** 
    *  This script uses ADODb, you must have ADOdb installed or in a common      *
    *  folder to run this script.  The best way to do this is to go to           *
    *  http://adodb.sourceforge.net/ and download the latest version and install *
    *  it in your include_path in the php.ini file.                              *
    ******************************************************************************/
    require_once ('adodb.inc.php'); 

    $db NewADOConnection('mysql');


    //MySQL database connection information
    $db->Connect("localhost","mike","mas4155","salesforce");

    //Truncate current database to establish a refresh
    $sql "TRUNCATE TABLE sforce_product2";
    if (
    $db->Execute($sql)) echo "<strong>Produc2 Table Truncated</strong><br />";

    //Salesforce Connection information
    $wsdl './includes/soapclient/partner.wsdl.xml';
    $userName "username";
    $password "password";


    //setup connection
    $client = new SforcePartnerClient();
    $client->createConnection($wsdl);
    $loginResult $client->login($userName,$password);

    //SOQL query for Object in Salesforce
    $soql "Select Id, Name, ProductCode, Description, IsActive, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, Family, IsDeleted,                 PRICE_PER_1K__c, PRICE_PER_5K__c FROM Product2 ";


    //Processes the query to get account information from Salesforce
    $records get_records($client,$soql,$db);

    if (
    $records === false)
    {
        
    //mail("mike.simonds@maxim-ic.com","PHP Product2 Script  Error","There has been an error in the product2 replication script\nPlease Check Script");
    }
    echo 
    '<p>There are currently '.$records.' products:</p>';

    $today date("F j, Y, g:i a");
    $end 'Product2 Import script ended at '.$today.' and inserted '.$records.' into the database';


    function 
    get_records($connection,$query,$db)
    {

        
    //Set this to the number of records to process per batch
        //200 is the minimum
        
    $queryOptions = new QueryOptions(1000);
        
    $connection->setQueryOptions($queryOptions);

        
    $response $connection->query(($query),$queryOptions);

        
    //for debugging
        //echo '<pre>' . print_r($response,true) . '</pre>';
        //exit;

        
    if ($response->size 0)
        {
            
    $records $response->records;
            
    // Cycles through additional responses if the number of records// exceeds the batch size
            
    $count_records 0;
            while (!
    $response->done)
            {
                
    $records $response->records;
                
    set_time_limit(100);
                
    ini_set("memory_limit","512M");


                
    //Process curent $records
                
    $current_count store_in_db($records,$db);

                if (
    $current_count === false)
                {
                    return 
    false;
                }
                else
                {
                    
    $count_records += $current_count;
                }
                echo 
    "processed ".$count_records." records<br />";
                
    flush();

                
    $response $connection->queryMore($response->queryLocator,$queryOptions);


            }
            
    set_time_limit(100);
            
    $records $response->records;
            
    //Process curent $records

            //store the last set of records into the database
            
    $current_count store_in_db($records,$db);

            if (
    $current_count === false)
            {
                return 
    false;
            }
            else
            {
                
    $count_records += $current_count;
            }
        }

        return 
    $count_records;
    }

    /*Function to store records into
    * database in chunks of the $queryOptions = new QueryOptions(200);*/
    function store_in_db($records,$db)
    {

        
    $record_count count($records);
        
    //echo $record_count;
        
    $rows_loaded 0;

        for (
    $i 0$i $record_count$i++) //foreach ($records as $r)
        
    {
            
    $r = new SObject($records[$i]);

            
    $pass_this['id'] = $r->Id;
            foreach (
    $r->fields as $key => $value)
            {
                
    $pass_this[$key] = addslashes($r->fields->$key);
            }


            
    $fields implode(",",array_keys($pass_this));
            
    $values implode("','",array_values($pass_this));
            
            
    $query "INSERT INTO sforce_product2 (".$fields.") VALUES ('".$values."')";


            
    //executes and loads data coming from salesforce into table
            
    if ($db->Execute($query))
            {
                
    $rows_loaded++;
            }
            else
            {
                echo 
    $db->ErrorMsg()."<br />";
                return 
    false;
            }
            
    //exit;
        
    }
        return 
    $rows_loaded;


    }

    ?>
    Right now it is set to replicate the product2 table in Salesforce to MySQL, but let's say I wanted to replicate and it is named export_product2.php.

    So let's say you wanted to replicate another object from Salesforce.

    So create your query! I do this by logging into the Salesforce Data loader and selecting all the fields

    Let's use the account object:

    so find
    PHP Code:
    $sql "TRUNCATE TABLE sforce_product2"
    and change it to:

    PHP Code:
    $sql "TRUNCATE TABLE sforce_account"
    this will wipe out all your data in your MySQL sforce_account table each time you run the replicate script, so new/fresh data is inserted


    so find the variable $soql in the script and change it from

    PHP Code:
    $soql "Select Id, Name, ProductCode, Description, IsActive, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, Family, IsDeleted,                 PRICE_PER_1K__c, PRICE_PER_5K__c FROM Product2 "
    TO

    PHP Code:
    $soql "Select Id, IsDeleted, MasterRecordId, Name, Type, ParentId, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry, ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, ShippingCountry, Phone, Fax, AccountNumber, Website, Sic, Industry, AnnualRevenue, NumberOfEmployees, Ownership, TickerSymbol, Description, Rating, Site, OwnerId, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, LastActivityDate, Account_Description__c, Area__c, End_Equipment__c, FY_CY_Auto_Info__c, FY_CY_Automotive__c, FY_CY_Communications__c, FY_CY_HSSP__c, SA_ID__c, FY_CY_Info_Comm__c, FY_CY_ISP__c, FY_CY_Micros__c, FY_CY_Mixed_Signal_1__c, FY_CY_Mixed_Signal_2__c, FY_CY_MM__c, FY_CY_Notebook__c, FY_CY_Optocon__c, FY_CY_SPC__c, FY_CY_SPM__c, FY_CY_SSIP__c, FY_CY_Thermal_Battery__c, FY_CY_Total_Design__c, FY_CY_Total_Purchasing__c, FY_CY_Wireless__c, Inactive__c, maxim_id__c, Region__c, Status__c, WebID__c FROM Account"
    then find (around line 140):

    PHP Code:

    $query 
    "INSERT INTO sforce_product2 (".$fields.") VALUES ('".$values."')"
    and change the table to sforce_account:

    PHP Code:
    $query "INSERT INTO sforce_account (".$fields.") VALUES ('".$values."')"
    rename the script to export_account.php and you have a replication script that you can run on CRON to replicate your account object and BAM! Here is the replication script for the account object:

    PHP Code:
    <?php
    ini_set
    ("soap.wsdl_cache_enabled","0");


    require_once (
    './includes/soapclient/SforcePartnerClient.php');

    /***************************************************************************** 
    *  This script uses ADODb, you must have ADOdb installed or in a common      *
    *  folder to run this script.  The best way to do this is to go to           *
    *  http://adodb.sourceforge.net/ and download the latest version and install *
    *  it in your include_path in the php.ini file.                              *
    ******************************************************************************/
    require_once ('adodb.inc.php'); 

    $db NewADOConnection('mysql');


    //MySQL database connection information
    $db->Connect("localhost","mike","mas4155","salesforce");

    //Truncate current database to establish a refresh
    $sql "TRUNCATE TABLE sforce_account";
    if (
    $db->Execute($sql)) echo "<strong>Account Table Truncated</strong><br />";

    //Salesforce Connection information
    $wsdl './includes/soapclient/partner.wsdl.xml';
    $userName "username";
    $password "password";


    //setup connection
    $client = new SforcePartnerClient();
    $client->createConnection($wsdl);
    $loginResult $client->login($userName,$password);

    //SOQL query for Object in Salesforce

    $soql "Select Id, IsDeleted, MasterRecordId, Name, Type, ParentId, BillingStreet, BillingCity, BillingState, BillingPostalCode, BillingCountry, ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, ShippingCountry, Phone, Fax, AccountNumber, Website, Sic, Industry, AnnualRevenue, NumberOfEmployees, Ownership, TickerSymbol, Description, Rating, Site, OwnerId, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp, LastActivityDate, Account_Description__c, Area__c, End_Equipment__c, FY_CY_Auto_Info__c, FY_CY_Automotive__c, FY_CY_Communications__c, FY_CY_HSSP__c, SA_ID__c, FY_CY_Info_Comm__c, FY_CY_ISP__c, FY_CY_Micros__c, FY_CY_Mixed_Signal_1__c, FY_CY_Mixed_Signal_2__c, FY_CY_MM__c, FY_CY_Notebook__c, FY_CY_Optocon__c, FY_CY_SPC__c, FY_CY_SPM__c, FY_CY_SSIP__c, FY_CY_Thermal_Battery__c, FY_CY_Total_Design__c, FY_CY_Total_Purchasing__c, FY_CY_Wireless__c, Inactive__c, maxim_id__c, Region__c, Status__c, WebID__c FROM Account";

    //Processes the query to get account information from Salesforce
    $records get_records($client,$soql,$db);

    if (
    $records === false)
    {
        
    //mail("mike.simonds@maxim-ic.com","PHP Product2 Script  Error","There has been an error in the product2 replication script\nPlease Check Script");
    }
    echo 
    '<p>There are currently '.$records.' products:</p>';

    $today date("F j, Y, g:i a");
    $end 'Product2 Import script ended at '.$today.' and inserted '.$records.' into the database';


    function 
    get_records($connection,$query,$db)
    {

        
    //Set this to the number of records to process per batch
        //200 is the minimum
        
    $queryOptions = new QueryOptions(1000);
        
    $connection->setQueryOptions($queryOptions);

        
    $response $connection->query(($query),$queryOptions);

        
    //for debugging
        //echo '<pre>' . print_r($response,true) . '</pre>';
        //exit;

        
    if ($response->size 0)
        {
            
    $records $response->records;
            
    // Cycles through additional responses if the number of records// exceeds the batch size
            
    $count_records 0;
            while (!
    $response->done)
            {
                
    $records $response->records;
                
    set_time_limit(100);
                
    ini_set("memory_limit","512M");


                
    //Process curent $records
                
    $current_count store_in_db($records,$db);

                if (
    $current_count === false)
                {
                    return 
    false;
                }
                else
                {
                    
    $count_records += $current_count;
                }
                echo 
    "processed ".$count_records." records<br />";
                
    flush();

                
    $response $connection->queryMore($response->queryLocator,$queryOptions);


            }
            
    set_time_limit(100);
            
    $records $response->records;
            
    //Process curent $records

            //store the last set of records into the database
            
    $current_count store_in_db($records,$db);

            if (
    $current_count === false)
            {
                return 
    false;
            }
            else
            {
                
    $count_records += $current_count;
            }
        }

        return 
    $count_records;
    }

    /*Function to store records into
    * database in chunks of the $queryOptions = new QueryOptions(200);*/
    function store_in_db($records,$db)
    {

        
    $record_count count($records);
        
    //echo $record_count;
        
    $rows_loaded 0;

        for (
    $i 0$i $record_count$i++) //foreach ($records as $r)
        
    {
            
    $r = new SObject($records[$i]);

            
    $pass_this['id'] = $r->Id;
            foreach (
    $r->fields as $key => $value)
            {
                
    $pass_this[$key] = addslashes($r->fields->$key);
            }


            
    $fields implode(",",array_keys($pass_this));
            
    $values implode("','",array_values($pass_this));
            
            
    $query "INSERT INTO sforce_account (".$fields.") VALUES ('".$values."')";


            
    //executes and loads data coming from salesforce into table
            
    if ($db->Execute($query))
            {
                
    $rows_loaded++;
            }
            else
            {
                echo 
    $db->ErrorMsg()."<br />";
                return 
    false;
            }
            
    //exit;
        
    }
        return 
    $rows_loaded;


    }

    ?>
    This script processes records in batch and that number is set with this line of code:

    PHP Code:
    $queryOptions = new QueryOptions(1000); 
    You can set that anywhere from 200 to 2000 (I think that 2000 is the max, but don't quote me on that)

    I hope this helps someone, let me know if anyone has any questions


    ~Mike

  2. #2
    vadugam is offline Junior Member
    Join Date
    Sep 2008
    Posts
    1

    Is there a way to capture triggers in salesforce and update our internal database

    Hi Mike

    We have a requirement , where we need to update our internal database , whenever the salesforce object gets updated.

    We have already migrated the data and we know the logic to update the salesforce whenever the internal database gets updated using the phptoolkit upsert SOQL commands .

    But whenever the salesforce object is updated, say i delete a account or contact in the salesforce , that corresponding account should get deleted in the internal database .

    Is there a way to do this . The requirement is that the data should be synchronized between the two databases (internal and the salesforce)


    we are using Mysql as the internal Database


    Kindly help me out

    Regards

    Krishna

  3. #3
    mike's Avatar
    mike is offline Administrator
    Join Date
    May 2007
    Location
    Wylie, Texas
    Posts
    557
    Blog Entries
    15
    Quote Originally Posted by vadugam View Post
    Hi Mike

    We have a requirement , where we need to update our internal database , whenever the salesforce object gets updated.

    We have already migrated the data and we know the logic to update the salesforce whenever the internal database gets updated using the phptoolkit upsert SOQL commands .

    But whenever the salesforce object is updated, say i delete a account or contact in the salesforce , that corresponding account should get deleted in the internal database .

    Is there a way to do this . The requirement is that the data should be synchronized between the two databases (internal and the salesforce)


    we are using Mysql as the internal Database


    Kindly help me out

    Regards

    Krishna
    There is a method in the toolkit called getupdated(), but I am not sure that will work for you

    I do not know if there is a way to accomplish what you are asking to be honest.

    There is a new feature on Salesforce called a trigger (like Oracle or MySQL), but I am not sure if a trigger can call an outside script to delete the record when it happens in Salesforce.

    I can try and find out and will, it would be a good thing


    Sorry if I lack the expertise for this, but I will do my best at finding an answer

    ~Mike

  4. #4
    salesforuse is offline Junior Member
    Join Date
    Sep 2008
    Posts
    4

    Post

    Hello Mike,

    Nice post and really helpful.

    I want to add my database records into my salesforce account contacts object.
    How I can make this reverse call from my server DB to salesforce account?

    Can u please help me out?

    Thanks,

    Salesforuse

  5. #5
    mike's Avatar
    mike is offline Administrator
    Join Date
    May 2007
    Location
    Wylie, Texas
    Posts
    557
    Blog Entries
    15
    Quote Originally Posted by salesforuse View Post
    Hello Mike,

    Nice post and really helpful.

    I want to add my database records into my salesforce account contacts object.
    How I can make this reverse call from my server DB to salesforce account?

    Can u please help me out?

    Thanks,

    Salesforuse
    Thanks for joining the site, I appreciate it!

    Sure I can help you out as much as I have time for.

    First let me ask you a couple of questions:

    1) What type of database is it (e.g. MySQL or Oracle)

    2) Did you have an external ID setup in your Contacts list?
    OR
    3) Do you have the Id field from the contacts object stored in your local DB?


    ~Mike

  6. #6
    salesforuse is offline Junior Member
    Join Date
    Sep 2008
    Posts
    4

    Thanks Mike

    Thanks Mike, really appreciated.

    Following are Q's and Answers:

    1) What type of database is it (e.g. MySQL or Oracle) Ans: Mysql


    2) Did you have an external ID setup in your Contacts list?
    Ans: yes, I am storing a Salesforce userid.
    OR
    3) Do you have the Id field from the contacts object stored in your local DB? Ans: No

    Please read following so you will have clear idea.

    Scenario:
    I am writing application which having one form with fields Name, City, Company. Salesforce user will fill up all fields and will submit form this request will get store in my server MYSQL DB. (I done with this). According to Salesforce user request I wanted to send a contacts to his Contact object those are matching to (Where Name, City, Company as fill up in form).
    I am not aware how I can send my records to Salesforce user Contact object. So that will add into his Salesforce account contact list.

    This is tricky part for me.

    For using API I have to know Username and Password for the user, but I am not sure that will get me in my S-control for application. Security concern is also there.


    Or you can also suggest me your idea of schema for my server DB table.


    I put whole idea and problem here.

    Waiting for your reply.

    Please help me out. Thanks a lot.



    Salesforuse.
    Last edited by salesforuse; 10-01-2008 at 09:36 AM.

  7. #7
    mike's Avatar
    mike is offline Administrator
    Join Date
    May 2007
    Location
    Wylie, Texas
    Posts
    557
    Blog Entries
    15
    Quote Originally Posted by salesforuse
    Please read following so you will have clear idea.

    Scenario:
    I am writing application which having one form with fields Name, City, Company. Salesforce user will fill up all fields and will submit form this request will get store in my server MYSQL DB.
    Glad that you are storing this data locally, this is good practice.


    Quote Originally Posted by salesforuse
    (I done with this). According to Salesforce user request I wanted to send a contacts to his Contact object those are matching to (Where Name, City, Company as fill up in form).
    I am not aware how I can send my records to Salesforce user Contact object. So that will add into his Salesforce account contact list.
    The contact object within salesforce is a child of the Account object (table). In order to create a contact, you need the accountId from Salesforce. Now I know that you said that you have the account name, but is it the Id from the account object? The minimum to create a new contact is 2 fields (LastName and AccountId).


    Quote Originally Posted by salesforuse
    For using API I have to know Username and Password for the user, but I am not sure that will get me in my S-control for application. Security concern is also there.

    If you are requiring the user to put their Salesforce user name and password in the form it would probably not allow that user to insert their own contacts into Salesforce. If the user profile of that user that is using your form has access to use the API. To check this, you would need to go to Setup > Administration Setup > Manage Users > Profiles

    I am not sure if this would be the best way to do it, but let me try to see if I can get this right:

    You have a form that is going to add a record to the contact object in Salesforce which has the following fields on it – Name, City, Company, Salesforce username, Salesforce password.

    You want to add this record to the users contact list in Salesforce.

    You will query your MySQL database to gather the information needed to populate the new record in Salesforce.

    Am I correct so far? Sorry I need more information on your local database and local data that you have stored.


    Sorry that I am asking so many questions, I just do not want to send you down the wrong path and develop the wrong kind of script!

    ~Mike

  8. #8
    salesforuse is offline Junior Member
    Join Date
    Sep 2008
    Posts
    4

    Thanks Mike!

    Thanks a lot Mike.

    Questions are most welcome as it will clarify our discussion.

    Quote:
    To check this, you would need to go to Setup > Administration Setup > Manage Users > Profiles
    Yes, I checked salesforec account is API Enabled . But I am not sure that each user of my application will have API enabled.

    Some explanation:

    • Application get install in Salesforce account of user and will listed in Salesforce user application list.
    • This Application will have tab, on click of tab it produce a form having suppose Name, city, company. Salesforce user will fill up the filtering criteria like Name, city, company and submit form.
    • It will directly submitting request to my server MYSQL database. Currently I am storing name, city, company, requested_by_salesforce_userid, requested_by_salesforce_name. Currently I am not storing username and password into table Or should I have?
    • Suppose there is one table in my server database with matching criteria records by MYSQL query I can sort it out. I need to push these records into the requested Salesforce user contact list. How I can implement this 4th step?

    Can we chat on this issue? Give me your messenger id.


    Your questions are most welcome

    Thanks a lot for help.

    Salesforuse

  9. #9
    mramsey is offline Junior Member
    Join Date
    Mar 2008
    Posts
    12
    I'm having a little issue with trying to replicate Leads into mysql.

    I've created the schema using the tools provided on this site (and i must say thanks for them).

    When using the script in this post (modified for leads table) i get errors when it tries to load row 1 says:

    Incorrect date value: '' for column 'ConvertedDate' at row 1

    I removed the ConvertedDate field from my soql query and get the following now:

    Incorrect datetime value: '2008-10-11T15:35:31.000Z' for column 'CreatedDate' at row 1

    Any help would be appreciated.

    Thanks,

    Mike Ramsey

  10. #10
    mike's Avatar
    mike is offline Administrator
    Join Date
    May 2007
    Location
    Wylie, Texas
    Posts
    557
    Blog Entries
    15
    Mike,

    I was able to get a full replication script working in a matter of a few minutes into MySQL.

    This is what I did:

    1) I used the scheme generator here and used my development account to create a full schema as you did (and thanks for the statement you made)

    2) I pulled the lead schema out of that file that was generated:

    Code:
    CREATE TABLE sforce_lead(
            Id VARCHAR(18),
            IsDeleted VARCHAR(5),
            MasterRecordId VARCHAR(18),
            LastName VARCHAR(80),
            FirstName VARCHAR(40),
            Salutation VARCHAR(40),
            Name VARCHAR(121),
            Title VARCHAR(80),
            Company VARCHAR(255),
            Street VARCHAR(255),
            City VARCHAR(40),
            State VARCHAR(20),
            PostalCode VARCHAR(20),
            Country VARCHAR(40),
            Phone VARCHAR(40),
            MobilePhone VARCHAR(40),
            Fax VARCHAR(40),
            Email VARCHAR(80),
            Website VARCHAR(255),
            Description TEXT,
            LeadSource VARCHAR(40),
            Status VARCHAR(40),
            Industry VARCHAR(40),
            Rating VARCHAR(40),
            AnnualRevenue INT(18),
            NumberOfEmployees INT,
            OwnerId VARCHAR(18),
            IsConverted VARCHAR(5),
            ConvertedDate DATE,
            ConvertedAccountId VARCHAR(18),
            ConvertedContactId VARCHAR(18),
            ConvertedOpportunityId VARCHAR(18),
            IsUnreadByOwner VARCHAR(5),
            CreatedDate DATETIME,
            CreatedById VARCHAR(18),
            LastModifiedDate DATETIME,
            LastModifiedById VARCHAR(18),
            SystemModstamp DATETIME,
            LastActivityDate DATE,
            SICCode__c VARCHAR(15),
            ProductInterest__c VARCHAR(255),
            Primary__c VARCHAR(255),
            CurrentGenerators__c VARCHAR(100),
            NumberofLocations__c INT(0)
        );
    3) then I took a script that I pulled off of this site and changed a few lines to point to the lead table, changed the SOQL statement to Salesforce to pull the data from the lead:

    PHP Code:
    <?php
    ini_set
    ("soap.wsdl_cache_enabled","0");


    require_once (
    './includes/soapclient/SforcePartnerClient.php');

    /*****************************************************************************
    *  This script uses ADODb, you must have ADOdb installed or in a common      *
    *  folder to run this script.  The best way to do this is to go to           *
    *  http://adodb.sourceforge.net/ and download the latest version and install *
    *  it in your include_path in the php.ini file.                              *
    ******************************************************************************/
    require_once ('adodb.inc.php');

    $db NewADOConnection('mysql');


    //MySQL database connection information
    $db->Connect("localhost","mike","mas4155","salesforce");

    //Truncate current database to establish a refresh
    $sql "TRUNCATE TABLE sforce_lead";
    if (
    $db->Execute($sql)) echo "<strong>Lead Table Truncated</strong><br />";

    //Salesforce Connection information
    $wsdl './includes/soapclient/partner.wsdl.xml';
    $userName "simonds@sportsrant.com";
    $password "mas4155qGDMotmYV5BFtSWBW8SBcf1Qa";


    //setup connection
    $client = new SforcePartnerClient();
    $client->createConnection($wsdl);
    $loginResult $client->login($userName,$password);

    //SOQL query for Object in Salesforce


    $soql "Select Id,IsDeleted,MasterRecordId,LastName,FirstName,Salutation,Name,Title,Company,Street,City,State,PostalCode,Country,Phone,MobilePhone,Fax,Email,Website,Description,LeadSource,Status,Industry,Rating,AnnualRevenue,NumberOfEmployees,OwnerId,IsConverted,ConvertedDate,ConvertedAccountId,ConvertedContactId,ConvertedOpportunityId,IsUnreadByOwner,CreatedDate,CreatedById,LastModifiedDate,LastModifiedById,SystemModstamp,LastActivityDate,SICCode__c,ProductInterest__c,Primary__c,CurrentGenerators__c ,NumberofLocations__c FROM Lead";

    //Processes the query to get account information from Salesforce
    $records get_records($client,$soql,$db);

    if (
    $records === false)
    {
        
    mail("masimonds@gmail.com","PHP Lead Export Script  Error","There has been an error in the Lead replication script\nPlease Check Script");
    }
    echo 
    '<p>There are currently '.$records.' Leads:</p>';

    $today date("F j, Y, g:i a");
    $end 'Product2 Import script ended at '.$today.' and inserted '.$records.' into the database';


    function 
    get_records($connection,$query,$db)
    {

        
    //Set this to the number of records to process per batch
        //200 is the minimum
        
    $queryOptions = new QueryOptions(1000);
        
    $connection->setQueryOptions($queryOptions);

        
    $response $connection->query(($query),$queryOptions);

        
    //for debugging
        //echo '<pre>' . print_r($response,true) . '</pre>';
        //exit;

        
    if ($response->size 0)
        {
            
    $records $response->records;
            
    // Cycles through additional responses if the number of records// exceeds the batch size
            
    $count_records 0;
            while (!
    $response->done)
            {
                
    $records $response->records;
                
    set_time_limit(100);
                
    ini_set("memory_limit","512M");


                
    //Process curent $records
                
    $current_count store_in_db($records,$db);

                if (
    $current_count === false)
                {
                    return 
    false;
                }
                else
                {
                    
    $count_records += $current_count;
                }
                echo 
    "processed ".$count_records." records<br />";
                
    flush();

                
    $response $connection->queryMore($response->queryLocator,$queryOptions);


            }
            
    set_time_limit(100);
            
    $records $response->records;
            
    //Process curent $records

            //store the last set of records into the database
            
    $current_count store_in_db($records,$db);

            if (
    $current_count === false)
            {
                return 
    false;
            }
            else
            {
                
    $count_records += $current_count;
            }
        }

        return 
    $count_records;
    }

    /*Function to store records into
    * database in chunks of the $queryOptions = new QueryOptions(200);*/
    function store_in_db($records,$db)
    {

        
    $record_count count($records);
        
    //echo $record_count;
        
    $rows_loaded 0;

        for (
    $i 0$i $record_count$i++) //foreach ($records as $r)

        
    {
            
    $r = new SObject($records[$i]);

            
    $pass_this['id'] = $r->Id;
            foreach (
    $r->fields as $key => $value)
            {
                
    $pass_this[$key] = addslashes($r->fields->$key);
            }


            
    $fields implode(",",array_keys($pass_this));
            
    $values implode("','",array_values($pass_this));

            
    $query "INSERT INTO sforce_lead (".$fields.") VALUES ('".$values."')";

            
            
    //executes and loads data coming from salesforce into table
            
    if ($db->Execute($query))
            {
                
    $rows_loaded++;
            }
            else
            {
                echo 
    $db->ErrorMsg()."<br />";
                return 
    false;
            }
            
    //exit;
        
    }
        return 
    $rows_loaded;


    }

    ?>
    4) I ran it on my localhost into my local database and it imported all the leads, 22 of them to be exact.

    I left my login for my Developers account in the script so you can test it for yourself

    *****Remember you must be using ADODB for this script to work, you can download ADODB database layer from my main menu on the home page*****

    so do let me know if this works, it should, and since you are in Dallas, Call me if you have any issues


    ~Mike

    PS: Remember to change the paths of all the includes to match your paths on your server

+ Reply to Thread
Page 1 of 3 1 2 3 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

SEO by vBSEO 3.5.1