Galahad MailChimp Synchronizer

The Galahad MailChimp Synchronizer lets you synchronize an existing mailing list with MailChimp. The synchronization is one-directional (from existing to MailChimp) so is most useful for keeping MailChimp synced with something like a membership database or customer list. A base class is provided, so that you can write any custom logic necessary for your particular database, and two implementations are also included (MySQLi and Array). The Array implementation lets you sync an array of e-mail addresses with MailChimp (mostly useful for testing, or very small lists). The MySQLi implementation lets you sync a MySQL database with MailChimp, assuming there is no major processing that has to happen outside of the database. Here’s a quick example of how you might use the MySQLi implementation:

require_once 'Galahad/MailChimp/Synchronizer/Mysqli.php';
require_once 'MailChimp/MCAPI.class.php';

$apiKey = 'ENTER YOUR API KEY HERE';
$list = 'ENTER YOUR LIST ID HERE';

$db = array(
	'host' => 'localhost',
	'username' => 'root',
	'passwd' => '',
	'dbname' => 'mailchimp',
);
$cols = array(
	'first_name' => 'FNAME',
	'last_name' => 'LNAME',
	'email' => 'EMAIL',
);

$selectQuery = 'SELECT email, first_name, last_name FROM `user`';
$existsQuery = 'SELECT COUNT(id) FROM `user` WHERE email = ?';

try {
	$synchronizer = new Galahad_MailChimp_Synchronizer_Mysqli($apiKey, $db);
    $synchronizer->sync($list, $selectQuery, $existsQuery, $cols);
	echo "\nSuccess";
} catch (Galahad_MailChimp_Synchronizer_Exception $e) {
    echo "\nError syncing: ", $e->getMessage();
}

A more complete example is included with the library files.

Keep in mind that if you get any individual errors (such as an invalid e-mail address or trying to sync someone who manually unsubscribed) the MailChimp API console will show errors for the listBatchSubscribe and listBatchUnsubscribe operations.

This is a pretty early version of the code, so you should test it thoroughly before using it.

Updated: Oct 5th, 2010 — Updated it to use the new API keys rather than a username and password, and also updated some API calls to match the latest version of the API.

Galahad MailChimp Synchronizer [96.14 kB]

And, by popular demand:


  • http://www.bluekaboom.com troy

    Thanks for the tip. We are looking for this solution to integrate in a ecommerce site. I will let you know how it goes. -T

  • Dave

    Works great! Kudos

  • Elan

    I get the following errors… suggestion?

    ————————————————-

    Started. 1. Method: login 2. Method: listMembers

    Warning: Invalid argument supplied for foreach() in /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/Galahad/MailChimp/Synchronizer.php on line 170

    Fatal error: Class ‘Galahad_MailChimp_Synchronizer_Exception’ not found in /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/Galahad/MailChimp/Synchronizer/Mysqli.php on line 171

    • http://cmorrell.com Chris Morrell

      Good call. Add this to the top of the Mysqli.php file:

      /** @see Galahad_MailChimp_Synchronizer_Exception */
      require_once dirname(__FILE__) . '/Exception.php';

      I’ll update the library in a bit.

  • Elan

    Now I get this response… and I am 90% sure I wrote the MySQL in ‘example-mysqli.php’ correctly:

    $existsQuery = ‘SELECT COUNT(id) FROM #__user WHERE email IS NOT NULL’;
    $query = ‘SELECT email, name, username FROM #__user’;
    $cols = array(
    ‘email’ => ‘EMAIL’,
    ‘name’ => ‘FNAME’,
    ‘username’ => ‘LNAME’,

    ——————————————–

    Started. 1. Method: login 2. Method: listMembers

    Fatal error: Uncaught exception ‘Galahad_MailChimp_Synchronizer_Exception’ with message ‘Error getting users from DB: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” at line 1′ in /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/Galahad/MailChimp/Synchronizer/Mysqli.php:176 Stack trace: #0 /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/Galahad/MailChimp/Synchronizer.php(210): Galahad_MailChimp_Synchronizer_Mysqli->getUsers(‘d1bea72165′, 0, 500) #1 /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/Galahad/MailChimp/Synchronizer.php(108): Galahad_MailChimp_Synchronizer->processLocalUsers(‘d1bea72165′) #2 /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/Galahad/MailChimp/Synchronizer/Mysqli.php(162): Galahad_MailChimp_Synchronizer->sync(‘d1bea72165′) #3 /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/example-mysqli.php(53): Galahad_MailChimp_Synchronizer_Mysqli->sync(‘d1bea72165′, ‘SELECT email, n…’ in /data/20/1/143/60/1958875/user/2138878/htdocs/mailchimp/Galahad/MailChimp/Synchronizer/Mysqli.php on line 176

    • http://cmorrell.com Chris Morrell

      I’m pretty sure that’s an error in your PHP query, but go ahead and try this getUsers function and let me know what error you get:

      protected function getUsers($listId = null, $batchNumber)
      	{
      		$start = $batchNumber * $this->_batchSize;
      		$result = $this->_db->query($this->_query . " LIMIT {$start}, {$this->_batchSize}");
      
      		if (false === $result) {
      			throw new Galahad_MailChimp_Synchronizer_Exception('Error getting users from DB.  MySQL said: "' .
      				$this->_db->error . '".  Query: "' . $this->_query . " LIMIT {$start}, {$this->_batchSize}\".");
      		}
      
      		$return = array();
      		while ($row = $result->fetch_assoc()) {
      			$user = array();
      			foreach ($this->_mergeColumns as $localColumn => $mcColumn) {
      				if (isset($row[$localColumn])) {
      					$user[$mcColumn] = $row[$localColumn];
      				}
      			}
      
      			$return[] = $user;
      		}
      
      		return $return;
      	}
      
  • Elan

    The previous reply I made to your code was actually my fault and should be deleted! The ‘Galahad_MailChimp_Synchronizer_Exception’ works great now and it was my SQL statement that was the problem… not your code.

    In fact I would like to not only apologize, but also extend a heartfelt and sincere gratitude for your development of this code. There is no one else offering this priceless code for the MailChimp API for free.

    I am a broke, journalist/novice web designer and was able to get this code to work on my own. When I needed help, the support you gave me was very friendly and then you offering further support was above and beyond the “call of duty”.

    If you have a donate button please let me know :-)

    Just a side note: the code for ‘getUsers’ listed above had the ‘>’ or ‘carrot’ sign replaced with html character ‘>’.

  • Elan

    When a user already exists in my database as well as on my MailChimp list, and where updates as well as no-updates exist, I get the below WARNING. Is this okay (only indicating a user already exists) or is there something wrong? Everything seems to work okay, including ListUnsubscribe when a user has been removed from my database, but I am worried that as the list becomes bigger this may become a burden on the server. What do you think?:

    ———————————————–

    Started. 1. Method: login 2. Method: listMembers

    Warning: mysqli_stmt::bind_param() [mysqli-
    stmt.bind-param]: Number of variables doesn’t
    match number of parameters in prepared statement in /data/20/1/143/60/1958875/user/2138878/htdocs
    /mailchimp_text/Galahad/MailChimp/Synchronizer
    /Mysqli.php on line 208

    3. Method: listBatchSubscribe Done.

  • oo

    Thanks for your script.
    I’m looking into it now and have some questions.
    My goal is to sync my db to mailchimp, including some fields and groups (1000 users first stage, 5000 second stage).

    http://www.mailchimp.com/api/examples/sync-you-to-mailchimp.php
    says: “Under NO circumstances should you setup a process that tries to sync EVERY on of your users to us on a regular basis!”

    I understand their reasons for writing this, but I also see they linked to your script from their site. Do I understand them wrong, or isn’t that colliding with your script’s concept? (assuming once a day sync operation).

    thanks again

    • http://cmorrell.com/ Chris Morrell

      This script actually doesn’t sync the entire db every time. It unsubscribes anyone that’s no longer in your local list and then subscribes everyone who is on your local list and is not on the MailChimp list, so you’re only transmitting NEW subscribers (and unsubscribing deleted users), not all of them.

  • http://www.worldofnakedmen.com Lance

    Hi Chris

    I am stuck and really appreciate you offering this script free!

    I am not sure if I am missing something but I have changed all the fields suggested but I keep getting this error:

    Fatal error: Call to a member function bind_param() on a non-object in /home/worldofn/public_html/ccc/Galahad/MailChimp/Synchronizer/Mysqli.php on line 203

    What am I doing wrong?

    Regards

    • http://cmorrell.com/ Chris Morrell

      Your userExistsQuery probably has a syntax error which is not letting Mysqli prepare it as a statement. Make sure that a) the query works if you manually replace the parameters, and b) it’s not using any functionality that cannot be used in a prepared statement (for example, you can’t do something like “LIMIT ?” and bind that).

  • Paul Thompson

    Hi Chris,

    I’m getting the following error but am not familiar with mysqli so don’t really understand it.

    I’ve checked the $email passed to the function is valid. Do you have any ideas?

    Fatal error: Call to a member function bind_param() on a non-object in /home/transpor/public_html/Galahad/MailChimp/Synchronizer/Mysqli.php on line 203

    • http://cmorrell.com/ Chris Morrell

      Your user exists statement probably either has a syntax error or is not compatible with prepared statements in it. Try debugging there (see above).

  • Marten

    Chris,

    Thank you so much for the script! Works like a charm!

    Regards,

    Marten (Netherlands)

  • http://SlumberPartyRecords.com Cody Peterson

    Chris! This is a great script thank you!

    I am having a little problem (probably with my sql statement). Can you take a look and see what looks funny to you/

    $existsQuery = ‘SELECT COUNT(ID) FROM wp_users WHERE user_email = ?’;
    $selectQuery = ‘SELECT user_email FROM wp_users’;

    Thanks!
    (p.s. I too would like to know where the donate button is :) )

    • http://cmorrell.com/ Chris Morrell

      What error are you getting, Cody? I don’t see anything immediately obvious in your statements.

  • Bill

    Hi Chris – First off, thanks for the great script.

    I have been trying to get it to work and read the previous posts to get me here.

    I have over 900 records imported into a MC list.
    The data was imported (csv) from an existing MySQL table. When I try to run the script to sync the table to the list, I get the following over and over again (I assume once for each record):

    Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn’t match number of parameters in prepared statement in /home/mysite/public_html/chimp/Galahad/MailChimp/Synchronizer/Mysqli.php on line 206

    At the end, I finally get this:

    4. Method: listBatchSubscribe 5. Method: listBatchSubscribe Done.

    Does that mean it worked? If so, is there a way to not show the errors – maybe just a progress indicator?

    Thanks in advance for your help,

    Bill

    • http://cmorrell.com/ Chris Morrell

      Bill, it looks like this might be a MySQL library error (I’ve found some references to that error in PHP bug reports). Try upgrading the libraries PHP uses to connect to MySQL and see if that helps.

  • Bill

    Hi again,

    Is it possible to add more fields besides fname,lname, and email? I have data in 3 custom fields that were imported during the initial import. Besides adding to the array, are there other changes? Just adding the fields in the array did not work.

    $cols = array(
    ‘first_name’ => ‘FNAME’,
    ‘last_name’ => ‘LNAME’,
    ‘email’ => ‘EMAIL’,
    ‘idnum’ => ‘IDNUM’,
    ‘class’ => ‘MEMBER_CLASS’,
    ‘firm’ => ‘FIRM’,

    );

    Thanks,

    Bill

    • http://cmorrell.com/ Chris Morrell

      As long as your select SQL query returns those columns, you should be fine.

  • Ian

    Does this handle deletes too or just adds?

  • http://cmorrell.com Chris Morrell

    It deletes members that are no longer in your local database and adds new
    members that aren’t in MailChimp. It was built to sync a ‘private’ local DB
    with a MailChimp list (so it’s not great for situations where you have folks
    subscribing in MC as well as getting added to the local database).

  • Rene

    Hey Chris,

    first of all i want to thank you about the script but i got an question,

    when i start the script this shows up:
    Started. 1. Method: login 2. Method: listMembers 3. Method: listBatchSubscribe Done.

    i thought the script did its job and went to look at mail chimp but there are no new subscribers.
    so whats wrong?

    thanks,

    Rene

  • http://cmorrell.com Chris Morrell

    Take a look at the sample code above. Grab the error checking portion and
    paste it in after $synchronizer->sync (lines 22-37). That should print out
    more detail about what’s going on.

  • Achamberas

    I am very new to php and APIs. I get the following error when I run this script. Is there a library that I need to install on my hosting site? I checked the API key in my mailchimp account and it matches (I x’d it out for this post). Am I missing something obvious?

    1. Method: login 2. Method: listMembers
    Warning: Invalid argument supplied for foreach() in /home2/apofacyc/public_html/MailChimp/Galahad/MailChimp/Synchronizer.php on line 170
    3. Method: listBatchSubscribe Error syncing: Error with batch subscribe: Invalid Mailchimp API Key: xxxxxxxxxxxxxxxxxxxxxxxxxx-us2 . You are accessing the wrong datacenter – your client library may not properly support our datacenter mapping scheme.

  • Achamberas

    nevermind. I figured it out. I had to add us2 to the line:

    $this->apiUrl = parse_url(“http://us2.api.mailchimp.com/” . $this->version . “/?output=php”);

    in the MCAPI.class. Works great!

  • Pingback: "Galahad MailChimp Synchronizer" by Chris Morrell

  • Regan

    Thanks Achamberas your solution works great.
    Please read below if you’re getting this error

    Warning: Invalid argument supplied for foreach() in /path/MailChimp/Galahad/MailChimp/Synchronizer.php on line 170

  • Regan

    Sorry please above…

  • http://cmorrell.com Chris Morrell

    I’ve updated the code to use the latest MailChimp PHP library, which should fix this error.

  • http://www.weddingvenues.com Bob

    Got the main upload working no problem but have a request.

    Any chance this could drop emails into specific groups within a list if the merge fields were also the group names?

    If you could explain how this could be done then let me know how much of a donation you’d like I’ll sort it out.

    Many thanks

    Bob

  • http://cmorrell.com Chris Morrell

    I don’t use MailChimp groups that much, so I’m not sure, but I think
    you should be able to just add an ‘INTERESTS’ column with the group
    names (comma separated) and you should be good.  For example, you
    might set your columns to:

    $cols = array(
         'first_name' => 'FNAME',
         'last_name' => 'LNAME',
         'email' => 'EMAIL',
         'groups' => 'INTERESTS',
    );
    

    That’s assuming an entry in your database looks something like:

    first_name: John
    last_name: Smith
    email: [email protected]
    groups: Group1,Group2

    Give that a try and see if it works.

  • http://www.weddingvenues.com Bob

    Hi Chris,

    Thanks for the help. Will give it a go and see what happens.
    Have a great weekend.

    Bob

  • Rod

    Hi, thanks for this code, it works very well. But Can I make a 2-way sync?
    and if yes, how?

    Greetings.
    Rod

  • http://cmorrell.com Chris Morrell

    It’s certainly not made for that, but you might be able to hack it. The
    simpler way would be to subclass the userExists() method so that whenever
    it’s called, it checks whether that email address is in the system, adds it
    if not, and always returns true. The downside of that method would be that
    you only get the email address in that method. Alternatively, you could
    subclass processMailChimpUsers(), but you’ll have to read through the code
    there and modify it accordingly. Essentially, you want to keep the first
    loop, and do your syncing within it, and just kill the second loop that
    handles unsubscribes.

    Hope that help!

    Chris

  • http://twitter.com/soundscolours Sounds and Colours

    I was wondering if anyone had worked out a solution where this could be used both as a local->remote sync and for new subscribers on a site. It looks like it would work absolutely perfectly for a sync that I’m hoping to do, but would also like to be able to use Mailchimp’s functionality for adding new subscribers and doing unsubscribes. The only thing I can think of is to have two Mailchimp accounts, one for syncing with a website, and one for syncing with a local database. Has anyone come up with any other solutions?

  • Arnold

    Are you sure? Because it seems to me that it subscribes anyone on your local list each time you sync:

    while($users = $this->getUsers($listId, $batch++, $this->_batchSize)) {
    $batchResult = $this->_mailChimp->listBatchSubscribe($listId, $users, $this->_mailChimpOptions['doubleOptIn'], true, true);

    Am I overlooking something?

  • http://cmorrell.com Chris Morrell

    Good point. The reason I do it that way is to sync all updates, too. But it does sort of go against what MailChimp suggests…

  • Wyllow

    Thanks Chris, works great so far. We just send you a donation.

  • Zarko

    Hi Chris!
    Thanks a lot for this script, it really saved my day :)
    I have a question tho, probably a silly one, but my query wouldn’t work. I’m trying to set the query sot that your sript updates only the newest entry in the db:
    $selectQuery = ‘SELECT name, email FROM `subscriptions` ORDER BY id ASC LIMIT 1′;
    But the error pops up:
    Fatal error: Class ‘Galahad_MailChimp_Synchronizer_Exception’ not found in /…/galahad-mailchimp-0.22/Galahad/MailChimp/Synchronizer/Mysqli.php on line 176.
    Is it because of the limit thing, or?

  • Zarko

    asc should be desc, naturally…

  • http://cmorrell.com Chris Morrell

    Yeah, the syncronizer adds its own LIMIT to the query, so you can’t use the
    LIMIT statement in your query. Sorry about that!

  • Claaschy

    Hi there
    Great script – thanks.
    Does anyone have a CGI script I could use to automate the sync daily, at say midnight?
    Thanks
    Claire

  • http://cmorrell.com Chris Morrell

    I just set up my PHP script as a CLI application
    and run it via the crontab.

  • Claaschy

    Hi Chris
    Thanks for the feedback, sadly I don’t have access to run cron jobs, so I’m looking for another way, any ideas?
    Thanks
    Claire

  • http://cmorrell.com Chris Morrell

    You can look into web-based cron
    alternatives.
    These sites essentially load a page on your website on given intervals,
    emulating cron. All you would do is put your MailChimp updater script
    somewhere public, and then tell one of these sites to ping it every day.

  • Alan

    Hi Chris! I’m excited to dig into your script. I’m a newbie, and I even just learned how to automatically synchronize a .csv file with a mysql database so the data would be ready for your mailchimp synchronizer.

    The only challenge is that I don’t want to delete members that are no longer in my local database. I just want to add any new members in the local database to the mailchimp database. The result, eventually, will be a mailchimp database which has more members than the local database.

    Would you be able to suggest a way to remove the delete function? Thanks so much!

  • http://cmorrell.com Chris Morrell

    Alan,

    Look at the sync method of the Galahad/Synchronizer.php file (line 105 in
    version 0.2). Just remove the $this->processMailChimpUsers($listId); line
    all together and it shouldn’t unsubscribe anyone.

  • Nathanael

    Hey there!

    First off, I’m sorry if I’m posting on a discussion. Hopefully you guys are still using this, and willing to help!

    Regarding the synchronization, what do you do if members are parts of different groups? How might I go about synchronizing their emails, names, AND the groups and subgroups they are a part of? Does anyone have a patch available, or know how to go about creating one? Is this already a feature, but I haven’t found it?

    Thanks for your help! :)

  • http://cmorrell.com Chris Morrell

    You just need to set a GROUPINGS parameter for each column. It should be an
    array in the form:

    array(
    ‘EMAIL’ => ‘[email protected]’,
    ‘FNAME’ => ‘John’,
    ‘LNAME’ => ‘Smith’,
    ‘GROUPINGS’ => array(
    array(
    ‘name’ => ‘Pets’,
    ‘groups’ => ‘Dogs,Birds’,
    ),
    array(
    ‘name’ => ‘Foods’,
    ‘groups’ => ‘Kibble,Canned,Seed,Treats’,
    ),
    )
    )

    You’ll have to extend the MySQL class and add your own getUsers() method to
    format the data returned by the database to match that format.

    Hope that helps!

    • Guest

      Hi. Love the script first off.

      Second, I would like this funcionality also; are you saying it’s currently in there or that we need to alter it in the way above?

      And is this the same for teh mysqli version?

      Thanks so much.

      • http://cmorrell.com Chris Morrell

        I think you’d have to subclass the Galahad_MailChimp_Synchronizer_Mysqli class, and modify the getUsers() method (in Mysqli.php).  Edit the while loop; it takes your $mergeColumns and adds them to an array to be sent to MailChimp.  Right now it maps columns 1:1 (for example, it maps a “user_email” column in MySQL to the “EMAIL” column in MailChimp).  You need to map your groups, however they’re formatted in the database, to the “GROUPINGS” MailChimp column, as described above.  This may mean that you have to add additional MySQL queries in that loop to pull the grouping information out of other tables (as 1:N relationships aren’t easy to query in this way).

        Hope that helps.  At first I thought it should be pretty easy, but looking at the code again I realize that it’s probably a bit of a chore.  Nothing killer, but you probably need to dedicate an hour or two to getting it right.

        Cheers,

        Chris

        • Guest

          I figured out using a join (inner in my case)  would fill the array, but subclassing it is still an issue. If I only have one group, say “company”, the class should work as-is, the problem arises when multiple groupings are needed, ie “company”, “admin”, “dept” groups.

          Maybe nest another if and implode the $localColumn?? 
           
          I agree, this is going to need some attention.

          Thanks for the reply

  • http://www.facebook.com/myflock Steve Lacy

    It’s working for me except when I delete a member from my local database, then re-run the sync script and it doesn’t delete the member(s) within Mailchimp that I removed from my local database. Am I doing something wrong? By the way I assumed the SQL that returns the count should be the count of those in your local list?

  • Sam

    What kind of table structure do you need. The post does not mentions anything beyond the database should be mailchimp.

  • Sam

    Hi,
    This definitely looks like a helpful tool. I encountered the following error, Please do provide help with the same.

    Notice: Undefined offset: 1 in C:Program FilesZendApache2htdocsmailchimpcodeMailChimpMCAPI.class.php on line 1999

    Fatal error: Class ‘Galahad_MailChimp_Synchronizer_Exception’ not found in C:Program FilesZendApache2htdocsmailchimpcodeGalahadMailChimpSynchronizer.php on line 181

  • http://cmorrell.com Chris Morrell

    You can have any database structure you want, as long as you can query a column with the user’s email address. When you set up the synchronizer you have to write a SQL statement that will select the appropriate columns from your table.

  • http://cmorrell.com Chris Morrell
  • http://cmorrell.com Chris Morrell

    Try downloading the latest version.

  • http://cmorrell.com Chris Morrell

    See my reply to Rod below. It’s not built to do it, but you could add that functionality if you want.

  • http://cmorrell.com Chris Morrell

    Try it now. I updated the code.

  • Weberiders

    Hey,
    That precisely is my question, What should be the table name and column name?
    Would it be table name :- user and columns: first_name, last_name,email and id.?

    The mysql_array example worked like a charm !!!

    Thanks.

  • George

    Hi Chris,

    Looks like a great plugin, however I’m having some trouble getting it to work. I’m using 0.2.1. If you could help me to understand what’s going on with this errors, it would be awesome:

    1) Invalid argument supplied for foreach() – reported as being on line 173 of Galahad/MailChimp/Synchronizer.php
    2) It doesn’t like my List ID. I’ve got a 6 digit numerical code from the end of the URL in the MailChimp control panel and used that.

    MailChimp is definitely picking up on the calls and associating them with my API key as they show up as failed calls from the the API page associated to my account

    Any help would be great

  • http://cmorrell.com Chris Morrell

    Your list ID is an alphanumeric code. Go to Lists, hover over the Settings link, and choose “list settings and unique id”. At the very bottom of the settings page there’s a unique ID field. Use that.

  • Jaydipsinh

    It’s definitely useful for sync…..Thanks

  • George

    Thanks heaps. Everything’s running fine now.

    Awesome plugin!

  • Glennonr

    Muchas Gracias for the Script.

    I’m getting the following error: Fatal error: Call to a member function bind_param() on a non-object in … /Galahad/MailChimp/Synchronizer/Mysqli.php on line 214

    Here is are my query statements:
    $selectQuery = ‘SELECT email, first_name, last_name FROM qryMailChimp’;
    $existsQuery = ‘SELECT COUNT(id) FROM qryMailChimp WHERE email = ?’;

    Any ideas?

  • http://cmorrell.com Chris Morrell

    Try version 0.2.2 — I added some error handling that at least should give you an error message with more details.

  • Glennonr

    Sorry for my ignorance… where do I get version 0.2.2?

    I downloaded from this link: http://cmorrell.com/downloads/1

    found on this page: http://cmorrell.com/open-source/galahad-mailchimp-synchronizer

    Is that not version 0.2.2?

  • http://cmorrell.com Chris Morrell

    Just download it again. I updated the file.

  • http://www.facebook.com/luke.danielson Luke Danielson

    Hey Chris. Sorry to bother you. It works perfect for me on the initial sync, when the entries are empty, but any syncs after that give me this:

    Fatal error: Uncaught exception ‘Exception’ with message ‘Table ‘filmdemi_demo2.user’ doesn’t exist’ in /home/filmdemi/public_html/demosite/mc_sync/Galahad/MailChimp/Synchronizer/Mysqli.php:214 Stack trace: #0
    /home/filmdemi/public_html/demosite/mc_sync/Galahad/MailChimp/Synchronizer.php(174): Galahad_MailChimp_Synchronizer_Mysqli->userExists(‘luke@filmdemic….’, ‘e497cc62de’) #1
    /home/filmdemi/public_html/demosite/mc_sync/Galahad/MailChimp/Synchronizer.php(110): Galahad_MailChimp_Synchronizer->processMailChimpUsers(‘e497cc62de’) #2
    /home/filmdemi/public_html/demosite/mc_sync/Galahad/MailChimp/Synchronizer/Mysqli.php(161): Galahad_MailChimp_Synchronizer->sync(‘e497cc62de’) #3
    /home/filmdemi/public_html/demosite/mc_sync/run.php(55): Galahad_MailChimp_Synchronizer_Mysqli->sync(‘e497cc62de’, ‘SELECT email_ad…’, ‘SELECT COUNT(id…’, Array) #4 {main} thrown in /home/filmdemi/public_html/demosite/mc_sync/Galahad/MailChimp/Synchronizer/Mysqli.php on line 214

    I am running from:
    http://reeldemic.com/demosite/mc_sync/run.php

    Any suggestions?

    THANKS!

    -Luke
    [email protected]

  • http://cmorrell.com Chris Morrell

    If you look at the error, you’ll see it says: Table ‘filmdemi_demo2.user’ doesn’t exist’ — the error is in your SQL code. I’m guessing you meant filmdemo_demo2?

  • http://www.facebook.com/profile.php?id=588096947 Moises Mejlachowicz
  • Andy

    Getting a not found when trying to download the script

  • http://cmorrell.com Chris Morrell

    Fixed! Sorry about that—I updated WordPress last night and forgot to update some configuration.

  • Joe

    Great – I got it working in 10 mins !

    Needed this badly

    thanks a lot

  • Kenneth

    Hi Chris Morrell!

    I was wondering if you maybe could help me with my sync code?

    In my list at Mailchimp i have 2 fields that i use, E-Mail and Name (which is with both last and first name) because thats the website was written, so i am unable to change that :(

    Now when i run the code below, i get a parse error and the website only loads everything down to where the sync code comes and then it stops, hope you can maybe point me in the direction to where i went wrong?

    require_once ‘Galahad/MailChimp/Synchronizer/Mysqli.php’;
    require_once ‘MailChimp/MCAPI.class.php’;

    $apiKey = ‘XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX’;
    $list = ’1′;

    $db = array
    (
    ‘host’ => ‘localhost’,
    ‘username’ => ‘XXXXXXXX’,
    ‘passwd’ => ‘XXXXXXXX’,
    ‘dbname’ => ‘XXXXXXX’,
    );

    $cols = array
    (
    ‘name’ => ‘NAME’,
    ‘email’ => ‘EMAIL’,
    );

    $selectQuery = ‘SELECT name, email FROM `lork_newsletter_users`’;
    $existsQuery = ‘SELECT COUNT(id) FROM `lork_newsletter_users` WHERE email = ?’;

    try {
    $synchronizer = new Galahad_MailChimp_Synchronizer_Mysqli($apiKey, $db);
    $synchronizer->sync($list, $selectQuery, $existsQuery, $cols);

    echo “nSynced:n”;

    // Print out log of sync actions
    foreach ($synchronizer->getBatchLog() as $entry) {
    echo “n – {$entry}”;
    }

    // Any individual errors
    $errors = $synchronizer->getBatchErrorLog();
    if ($errors) {
    echo “nnErrors:n”;
    foreach ($errors as $batch => $batchErrors) {
    echo “n{$batch}:”;
    foreach ($batchErrors as $error) {
    echo “n – {$error['message']}”;
    }
    }
    }
    } catch (Galahad_MailChimp_Synchronizer_Exception $e) {
    echo “nError syncing:nn”;
    echo $e->getMessage();
    }

    • http://cmorrell.com Chris Morrell

      Can you be more specific about where the parse error is? It should tell you what line and what file. Find that line in your code, and the few lines around it, and paste it into a reply or email it to me…

      • Kenneth

        Well i don’t get any errors, as soon the server hits the code pasted above it stop parsing code and returns only what it went throught before it hit the above pasted code, like the HTML head tags and body start tag.

        I did not include any additional code that could be the problem, i just copy pasted your code and tweaked it so it fitted my DB, what is your e-mail so i can contact you, think that would work better than writing here :)

        • Kenneth

          Sorry Chris!

          I’v been a smock of almost biblical proportions :)

          Found my error now! (helps supplying the correct DB username) But thanks for the quick answer thou :D

  • Ben Duffin

     How might i pass the date of subscription into Mailchimp? Im having trouble finding the name for the $cols key … feel a bit stupid too! managed to do everything else including 2-way syncing but I can’t figure out how to pass the date variable from our MySQL table into the Mailchip – we thought it was CONFIRM_TIME but that does not seem to be the case!

    • http://cmorrell.com Chris Morrell

      I’m actually not sure if you can pass the date of subscription… it might always use the current timestamp.  But you can always take a look at the MailChimp API docs and see if you can find anything.

  • Ospreys

    Hi Chris
    Great script and just what I need.  I have a problem running it though, so can you help?

    I get the following error:

    Warning: Invalid argument supplied for foreach() in /home/rainbowp/public_html/ros/Galahad/MailChimp/Synchronizer.php on line 173Error syncing: Error getting users from DB: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘FROM `cust` LIMIT 0, 500′ at line 1

    • http://cmorrell.com Chris Morrell

      It sounds like an error in your SQL.  Can you paste it here so I can look at it?

      • Ospreys

        Hi Chris
        This is what I have.  I have just adjusted for my DB:

        $selectQuery = ‘SELECT email, surname, firstname, FROM `cust`’;$existsQuery = ‘SELECT COUNT(cust_id) FROM `cust` WHERE email = ?’;

        • http://cmorrell.com Chris Morrell

          There’s an extra comma after firstname in your SELECT query.  It should be:

          $selectQuery = ‘SELECT email, surname, firstname FROM `cust`’;

      • Ospreys

        arGHH… I can’t believe I missed that.  Thanks Chris.

  • Ospreys

    Chris
    Is there anything wrong with this query?

    $selectQuery = ‘SELECT email, surname, firstname FROM `cust`                 WHERE date_entered >= (`2011/04/01`, `yyyy/mm/dd`) AND date_entered ‘FNAME’, ‘surname’ => ‘LNAME’, ‘email’ => ‘EMAIL’, ‘date_entered’ => ‘DATE_ENTER’,);

    • Ospreys

      Think I just spotted my mistake O:)

      • Ospreys

        No I haven’t spotted the mistake. I thought adding date_entered into the select would work.

        SELECT email, surname, firstname, date_entered FROM `cust`

        Chris, do you know why this doesn’t work?
        >>>
        Error syncing: Error getting users from DB: Unknown column ’2011/04/01′ in ‘where clause’
        <<<

        • Ospreys

          Ok, I got this query to work:
          SELECT email, surname, firstname, date_entered FROM `cust`                 WHERE cust.date_entered between “2011/04/01″ AND “2011/04/30″

          Had to use double quotes.

          Although it seemed to run ok – when I checked the Mailchimp list it hadn’t removed any of the other records and still displayed the original 9,000 odd records.  I thought it would sync and unsubscribe everything except for the 192 records that the query should have returned???

          Is this the way it is supposed to work?

    • http://cmorrell.com Chris Morrell

      You’re using backticks, which indicate a column (you should be using single or double quotes).  Also, I’ve never seen dates queried like that.  I would just do:

      WHERE `date_entered` >= ’20110401′

      • Ospreys

        Thanks Chris.  
        Got that query running now.  Just need to know how the script works now.  If I have a list on Mailchimp say of 1,000 records and I change the query to pull just records for the last 24hrs. Does the script then unsubscribe all of the 1,000 records that were not inserted in the last 24hrs?

        • http://cmorrell.com Chris Morrell

          Yes—it should unsubscribe anyone who’s not in your local list.  Grab the batch log using the getBatchLog() method to see a log of what the synchronizer did (make sure it says it’s unsubscribing).  Also, make sure that your $userExistsQuery is set correctly.  The script calls userExists($email, $listId) on each email address in MailChimp, and batch unsubscribes them if it returns false.  So if your script is not unsubscribing anyone, something is messed up.

  • http://www.facebook.com/ralph.vugts Ralph Vugts

    I have a column in Mailchimp called DATEADDED which I want to push a date to, I have the date formate set to day/month/year in mailchimp but struggling to get it to update.

    Code:
    $Today = date(“dmY”);

    $cols = array(
        ‘fname’ => ‘FNAME’,
        ‘lname’ => ‘LNAME’,
        ‘email’ => ‘EMAIL’,
        $Today => ‘DATEADDED’,   
    );

    Doesn’t seem to work… any ideas?

    • http://www.facebook.com/ralph.vugts Ralph Vugts

      Never mind, got it to work by pulling the date from the database instead

  • scott.d

    Hey Chris,

    I am getting this error.

    Fatal error: Class ‘mysqli’ not found in Galahad/MailChimp/Synchronizer/Mysqli.php on line 99

    Any ideas?

    • http://cmorrell.com Chris Morrell

      It sounds like you don’t have the MySQLi extension installed.  Make sure you’re running PHP 5+ and if so, follow the instructions on http://www.php.net/manual/en/mysqli.installation.php to enable MySQLi (unfortunately, you’ll have to recompile to enable it).

  • Emile

    Chris, getting this error after sync:
    Error with batch unsubscribe: You must specify a emails value for the listBatchUnsubscribe method

    That’s got to be a bug right? Any ideas?

    Thanks!

  • Emile

    Nevermind, got it sorted out. I was using version 1.3 of MailChimp class while your included version in 1.2.

    So this won’t work with 1.3 just yet, some issue there.

  • Joaoptmmg

    chris ,could u help me please? i  am trying  to sync  the custumer lists from goldmine to mailchimp . i dont know what these APIs are and how to use them .
    i HAve some knowledge of PHP but thats all.

    • http://cmorrell.com Chris Morrell

      Sorry—I have no experience with goldmine. If you run across a specific but I can try to help out, but that’s about it…

  • Rick

    Hi Chris, wondering if you could help me implement your galahad with an existing sql database?  Not sure  if you work like that or not?

    • http://cmorrell.com Chris Morrell

      Sorry, I don’t really do any contract work any more. Look through the Mysqli examples and you should be able to figure it out, though. If you have a specific issue, feel free to post it and I’ll try to help…

  • CappyTex

    When mail is sent to subscribers, there are links from Mailchimp for them to update their e-mail address (and other information). What’s the best way to get these updates posted back to my database?

    • http://cmorrell.com Chris Morrell

      What we do is just use our own links to update their info. So instead of linking to the MailChimp ‘options’ page, we link to our internal ‘profile’ page. If you want two-way sync you’re going to have to look elsewhere (I’m pretty sure such scripts exist, though).

  • Eamon Bisson-Donahue

    Thanks for this. Saved my much time and significant stress!!!

  • Paul Gutches

    ok… just wrote a comment about the invalid argument error.  turns out I was using MailChimp’s latest download of the api, and not the one provided with Galahad.    works like a charm now!

  • Plinkslink

    Hi, cheers for the code. Im only new to working with mysql but this looks like i could use it for a project im working on at the minute. 

    Pardon my stupidity but ive defined my database variables and what i want synced ….// =============================================================================
    //  SET THESE
    // =============================================================================
    $apiKey = ‘removed’;
    $list = ‘removed’;
    $db = array(
        ‘host’ => ‘removed’,
        ‘username’ => ‘removed’,
        ‘passwd’ => ‘removed’,
        ‘dbname’ => ‘removed’,
    );
    $cols = array(
        ‘name’ => ‘Name’,
        ‘email’ => ‘Email’,
        ‘List1′ => ‘Province’,
        ‘List2′ => ‘County’,    
        ‘List3′ => ‘Town’,   
        ‘constant’ => ‘constant’,  
    );
    $selectQuery = ‘SELECT name, email, List1, List2, List3, constant FROM `29711el`’;
    $existsQuery = ‘SELECT COUNT(id) FROM `29711el` WHERE name = ?’;…. but am unsure how to execute the sync. Any advice?

    • http://cmorrell.com Chris Morrell

      You need to run the code from your command line. Usually folks set it up to run via cron.

  • Ralph Vugts

    Hi there, I just got an “API login() Shutdown Notice” from Mailchimp… any chance of an updated version of this script?

  • http://twitter.com/freepowerpoint Free Powerpoint

    Worked fine except for merge fields. I didn’t see the merge tags working after running the script. Thanks for this great sync tool, indeed.

  • http://www.outsource-website-design.com website outsourcing

    Good advice and i absolutely enjoyed to read this articles, its a good entertainment. i think most of the peoples are brand your advisory column , because its accepting enjoyment. so thanks for your abundant advisory post.

  • Anonymous

    hi Chris, thank you for offering this wonderful script for free!

    I’ve got a question. I’m currently developing a contact management system which also sync with the list in mailchimp. Users can select any contacts in the system, update the details like name/email then click update. Upon updating the local database, i also wish the data in mailchimp to be updated too. 

    Does your script allows a specific contact in mailchimp to be synced?

    Thank you!

    • http://cmorrell.com Chris Morrell

      This script was mostly built to keep a MailChimp list entirely synchronized with a local list.  Whenever you make changes locally, they’re pushed to MailChimp when the script runs.  So yes, it does do what you want, but I think that more specialized code would be better for you, especially if you have a lot of customers connecting the many different lists.  Just look into the MailChimp API.  It should be pretty easy to push your changes on update, rather than in batches via cron.

  • Anonymous

    hi Chris, thank you for offering this wonderful script for free!

    I’ve got a question. I’m currently developing a contact management
    system which also sync with the list in mailchimp. Users can select any
    contacts in the system, update the details like name/email then click
    update. Upon updating the local database, i also wish the data in
    mailchimp to be updated too. 

    Does your script allows a specific contact in mailchimp to be synced?

    Thank you!

  • http://www.webhostings.in/ web hosting companies

    Above the review is very helpful to improve my knowledge.Every one looking for this kind of information.

  • http://www.webhostings.in/ web hosting companies

    Above the code is very helpful to solve my query very quickly.