Obama '08

               
   

Go Back   Mike Simonds > Salesforce > Salesforce PHP Tutorials

This is a discussion on Salesforce Code Example #1 within the Salesforce PHP Tutorials forums, part of the Salesforce category; Here is the full code of the first tutorial PHP Code:  

Reply
 
LinkBack Thread Tools Rate Thread
  #1  
Old 05-16-2007, 02:40 PM
Administrator
 
Join Date: May 2007
Posts: 246
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;
    }
}
?> 
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #2  
Old 07-31-2007, 10:20 PM
Unregistered
Guest
 
Posts: n/a
help me

i want to know, what its mean

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

i want to try that php, but i cant to resolve myself

thank you
Randy Thio
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3  
Old 08-01-2007, 02:27 AM
Unregistered
Guest
 
Posts: n/a
'{'

Quote:
Originally Posted by Unregistered View Post
i want to know, what its mean

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

i want to try that php, but i cant to resolve myself

thank you
Randy Thio
i want to ask again, why your program when i debug, there area some error like "error, parse error, unexpected '{' in line 177
i see that the open '{', also there is a close '}'

thank you
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4  
Old 08-01-2007, 04:05 AM
Unregistered
Guest
 
Posts: n/a
question

Quote:
Originally Posted by mike View Post
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;
    }
}
?> 


i had already download you koding, then when i try to my computer, there is an error
can you explain to me, how to resolve the error ??

thank you
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5  
Old 08-01-2007, 12:00 PM
Administrator
 
Join Date: May 2007
Posts: 246
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
Smile Need more information

Quote:
Originally Posted by Unregistered View Post
i had already download you koding, then when i try to my computer, there is an error
can you explain to me, how to resolve the error ??

thank you
What error code are you getting? Are you using oracle? > that is the type of database that this script/tutorial is going against. What exactly are you trying to do? I need to know more information about what you are seeing!

Thanks,
Mike
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6  
Old 08-01-2007, 09:00 PM
Unregistered
Guest
 
Posts: n/a

Quote:
Originally Posted by mike View Post
What error code are you getting? Are you using oracle? > that is the type of database that this script/tutorial is going against. What exactly are you trying to do? I need to know more information about what you are seeing!

Thanks,
Mike
that error
Fatal error: Class 'SoapClient' not found in C:\Documents and Settings\Johan\My Documents\Visual Studio Projects\PHP Project4\includes\soapclient\SforceBaseClient.php on line 91

i just see it, then i think soapclient isnot deklare
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7  
Old 08-01-2007, 09:33 PM
Unregistered
Guest
 
Posts: n/a

i want to ask again, can u explain to me what its operator mean
"->"
e.g. $this->sforce = new SoapClient($wsdl,$soapClientArray);

i search at google, i dont found the result
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8  
Old 08-01-2007, 10:11 PM