You are here

14 March 2014

First you need to add the connection information of the other database. This way you can use drupal database abstraction layer for altering any database.

Source code viewer
  1. Database::addConnectionInfo('mydb', 'default', array(
  2. 'driver' => 'mysql',
  3. 'database' => 'my_database',
  4. 'username' => 'root',
  5. 'password' => '',
  6. 'host' => 'localhost',
  7. ));
  8.  
  9. // Run select query on table data.
  10. $results = Database::getConnection('default', 'mydb')
  11. ->select('data', 'd')
  12. ->fields('d')
  13. ->execute()
  14. ->fetchAll();
  15.  
  16. // Iterate through results.
  17. foreach($results as $result) {
  18. $fields = (array)$result;
  19. unset($fields['publicationid']);
  20. // Alter results.
  21. foreach($fields as &$field) {
  22. $field = base64_decode($field);
  23. $field = iconv('windows-1257', 'UTF-8', $field);
  24. }
  25. // Save the data back.
  26. try {
  27. $count = Database::getConnection('default', 'mydb')
  28. ->update('data')
  29. ->fields($fields)
  30. ->condition('publicationid', $result->publicationid)
  31. ->execute();
  32. }
  33. catch (Exception $e) {
  34. drupal_set_message(t('Query failed message = %message, query= %query',
  35. array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
  36. }
  37. }
Programming Language: PHP