View Single Post
  #1  
Old 05-16-2007, 03:40 PM
mike mike is offline
Administrator
 
Join Date: May 2007
Posts: 273
Send a message via AIM to mike Send a message via MSN to mike Send a message via Yahoo to mike Send a message via Skype™ to mike
Salesforce Code Example #1

Here is the full code of the first tutorial

PHP Code:
 // Start of code here

error_reporting(E_ALL & ~ E_NOTICE);

// Login to salesforce.com

//this clears out your local PHP WSDL cache incase you may have been performing
//tests against your development account or Sandbox account
ini_set("soap.wsdl_cache_enabled""0");
require_once (
'./includes/soapclient/SforcePartnerClient.php');
require_once (
'./includes/soapclient/SforceHeaderOptions.php');


// Salesforce Login information
$wsdl './includes/soapclient/partner.wsdl.xml';
$userName "myemail@email.com";
$password "salesforce password";

// Process of logging on and getting a salesforce.com session
$client = new SforcePartnerClient();
$client->createConnection($wsdl);
$loginResult $client->login($userName$password);

if (!
$loginResult->passwordExpired)
{

    
// Connect to ADO database
    
require_once ('adodb.inc.php');# load code common to ADOdb

    
$conn ADONewConnection("oci8");

    
//connect to new database
    
$_ret $conn->Connect(''"database user""password""database");

    if (
$_ret)
    {

        
// Set initial parameters
        
$number_records 200;// set the amount of records to process at one time, and also the amont to increment the session variable by each iteration
        
$record_count $number_records;
        
$starting_record 1;// will start at the first record, then will increment by $number_records each iteration
        
$tab "\t";
        
$cr "\n";


        
//Reset counters for accounts
        
$accounts_created 0;
        
$accounts_updated 0;
        
$accounts_failed 0;

        
//Cleans up old files from past runs and re-creates the /files folder
        
delete_directory('./files');
        
mkdir("./files"0777);


        
//Adds Run Date to File name
        
$date date("mdy_hia");
        
$savepath './files';

        
//Creates log fiels which can be  emailed to distro list
        
$data1 "Account" ',' "External Id" $cr;
        
$file_created "$savepath/accounts_created_".$date.".csv";
        
$fp fopen($file_created"a");// $fp is now the file pointer to file $filename
        
fwrite($fp$data1);//    Write information to the file
        
fclose($fp);

        
$data2 "Account" ',' "External Id" $cr;
        
$file_updated "$savepath/accounts_updated_".$date.".csv";
        
$fp fopen($file_updated"a");// $fp is now the file pointer to file $filename
        
fwrite($fp$data2);//    Write information to the file
        
fclose($fp);

        
$data2 "Account,External Id,Error Message" $cr;
        
$file_failed "$savepath/accounts_failed_".$date.".csv";
        
$fp fopen($file_failed"a");// $fp is now the file pointer to file $filename
        
fwrite($fp$data2);//    Write information to the file
        
fclose($fp);

        while (
$record_count == $number_records)
        {

            
// Reset the php execution time to 20 seconds every time we get new
            // records from the database
            
set_time_limit(20);


            
$sql "SELECT   id AS ownerid,
                    external_id as \"external_field__c\",
                    address as \"business address\"
                    FROM database_table
                    WHERE ROWCOUNT BETWEEN $starting_record AND ($starting_record + ($number_records-1))
                    ORDER BY ROWCOUNT"
;

            
$recordSet $conn->Execute($sql);

            
$all_fields = array();
            
$i 0;
            while (
$row $recordSet->FetchRow())
            {
                
$all_fields[$i]['OWNERID'] = $row['OWNERID'];
                
$all_fields[$i]['EXTERNAL_FIELD__C'] = htmlspecialchars(stripslashes(strip_tags($row['EXTERNAL_FIELD__C'])));
                
$all_fields[$i]['BILLINGADDRESS'] = htmlspecialchars($row['BILLINGADDRESS']);
                
// You can add addtional rows here if needed
                
$i++;
            }

            
$record_count $i;

            
$sObjects = array();

            foreach (
$all_fields as $fieldset)
            {
                
$sObject = new sObject();
                
$sObject->type 'Account'// Salesforce Table or object that you will perform the upsert on
                
$sObject->fields $fieldset;
                
array_push($sObjects$sObject);
            }
            
//This passes the client = the login to sales force
            // the $sObjects = data to upsert
            // $file_updated = accounts which are updated
            // $file_created = accounts which are inserted
            // $file_failed =  accounts which failed
            
$success upsert_accounts($client$sObjects$file_updated$file_created$file_failed);

            
// Update the overall counts
            
if (is_array($success))
            {
                
$accounts_created $accounts_created $success[0];
                
$accounts_updated $accounts_updated $success[1];
                
$accounts_failed =  $accounts_failed $success[2];
            }

            
$starting_record $starting_record $number_records;

            
ob_start();
            
$total_record_count $total_record_count $record_count;
            echo 
$total_record_count." records processed.
"
;
            
ob_end_flush();
        }

        
// Close database connection after all rows have been retrieved
        
if ($conn)
        {
            
$conn->Close();
        }

    }
    else
    {
        
// There was an error connecting to the database
        
$msg 'Cannot connect to Database';
        
$msg $msg 'Error: ' $conn->ErrorMsg();
        echo 
$msg;
    }
}
else
{
    echo 
"Unable to connect to salesforce.com.";
}




/************************
*  Salesforce Functions *
*************************/
function upsert_accounts($client$sObjects$file_updated$file_created$file_failed)
{
    
$accounts_created 0;
    
$accounts_updated 0;
    
$accounts_failed 0;
    try
    {
        
// The upsert process
        
$results $client->upsert("external_field__c"$sObjects);

        
$k 0;

        
// This loop processes $result to build the log files
        
foreach ($results as $result)
        {
            
// Build string from fields in $sObjects array
            // At this point, the record has already been upserted
            // We just need the data for the log file
            // The string is the same, regardless of the result
            
$data2 $sObjects[$k]->fields['NAME'] . ", " $sObjects[$k]->fields[
                
'external_field__c'];

            if (
$result->success)
            {
                if (
$result->created)
                {
                    
$accounts_created++;
                    
file_put_contents($file_created$data2 "\n"FILE_APPEND);
                }
                else
                {
                    
$accounts_updated++;
                    
file_put_contents($file_updated$data2 "\n"FILE_APPEND);
                }
            }
            else
            {
                
$accounts_failed++;
                
// The errors object also contains fields and status_code
                
$errMessage $result->errors->message;
                
file_put_contents($file_failed$data2 ", " $errMessage "\n"FILE_APPEND);
            }
            
$k++;
        }
        
// Put the result counts into an array to pass back as the result.
        
$success = array();
        
array_push($success$accounts_created$accounts_updated$accounts_failed);
        return 
$success;
        exit;
    }
    catch (
exception $e)
    {
        
// This is reached if there is a major problem in the data or with
        // the salesforce.com connection. Normal data errors are caught by
        // salesforce.com
        
echo '' print_r($etrue) . '';
        return 
false;
        exit;
    }
}
?> 
Reply With Quote