cancel
Showing results for 
Search instead for 
Did you mean: 

API crashes when someone is already in database...please help

Occasional Visitor

API crashes when someone is already in database...please help

I have a php form that is for a weekly contest... when people sign up for the contest the information gets sent to my CC database and also sends me an email with the info. Problem is that if the person already exists in the database the code just crashes. Help please. Let me know what you need to see to help me fix. Thanks!

1 REPLY 1
CTCT Employee

Re: API crashes when someone is already in database...please help

Hi,

 

We have a rest-based API, so contact updates have to be handled differently than brand new contacts.  We advise doing a search to see if a contact exists, and then add it if it doesn't and update it if it does already exist.  Here is the PHP code I use to do this.  It uses our PHP wrapper.

 

<?php

session_start ();
require_once 'ConstantContact.php';
require_once 'config.php';

$ConstantContact = new ConstantContact("oauth2", $apiKey, $username, $accessToken);  //OR
//$ConstantContact = new ConstantContact("basic", $apiKey, $username, $password);
//Supply your credentials--API Key and other details--in config.php

// Get potential contact lists
$lists = $ConstantContact->getLists();
// Lists are returned in multidimentional arrays 0 being the list, and 1 being the next50

// Email address here is used for testing purposes
$emailAddress = "test_12132012@example.com";

// Search for our new Email address
$search = $ConstantContact->searchContactsByEmail($emailAddress);

// If the search didnt return a contact object
if($search == false)
{
	// Create a new Contact Object to store data into
	$contactObj = new Contact();
	// Adding multiple lists to this new Contact Object
	$contactObj->lists = array($lists['lists'][0]->id, $lists['lists'][1]->id);
	// Set the email address
	$contactObj->emailAddress = $emailAddress;
	//Set the opt in source
	$contactObj->optInSource = "ACTION_BY_CONTACT";
	// Create the Contact and DONE
	$Contact = $ConstantContact->addContact($contactObj);
	echo ("Contact added.");

} // Otherwise we update our existing contact
else 
{
	// Gather data from our previous search and store it into a data type
	$contactObj = $ConstantContact->getContactDetails($search[0]);

	// We need to get the old list and add a new list to it as
	// this request requires a PUT and will remove the lists
	// as they are stored in an array
	 array_push($contactObj->lists, $lists['lists'][1]->id );
	 //Set the opt in value
	 $contactObj->optInSource = "ACTION_BY_CONTACT";
	// Update the contact and DONE
	$UpdateContact = $ConstantContact->updateContact($contactObj);
	echo ("Contact updated.");
}	

?>

 

 

Best Regards,

Shannon W.

API Support Specialist