<p>Brad is absolutely correct. Better off trying for an existing plugin (we have one in the works over here for very robust Wordpress migrating!!!), but here are a few steps to get you started:</p>

<p>Move the non-craft database tables over to a staging server with your craft tables, and rename them with a craft_ prefix (or whatever you have set as your prefix in config). 
Query for the entries</p>

<pre><code>$query = craft()-&gt;db-&gt;createCommand()
-&gt;select('*')
-&gt;from('your-non-craft-post-table')
-&gt;where('any conditions')
-&gt;queryAll();
</code></pre>

<p>Loop through the query results, creating new Entry Models and assigning columns to your fields.</p>

<pre><code>//Go through each $query result
foreach($query as $old_entry){
    $entry = new EntryModel();
    $entry-&gt;sectionId = your_craft_section_id;
    $entry-&gt;authorId = your_craft_user_id;
    $entry-&gt;postDate = $old_entry['old_post_date_column'];
    $entry-&gt;enabled = true;

    //This is the fun part - mapping content to your custom fields
    $entry-&gt;getContent()-&gt;title = $old_entry['old_title_column'];
    $entry-&gt;getContent()-&gt;yourCustomFieldHandle = $old_entry['column_to_map_to_custom_field'];

    //Use the Entries service to save the new entry
    $success = craft()-&gt;entries-&gt;saveEntry($entry);
}
</code></pre>

<p>Obviously there is more to it than that...mapping user accounts, categories, tags, assets, etc. But hopefully this will help you get started!</p>

CC BY-SA 3.0
2015-02-03T15:01:35.080Z
Side note: If you have relations you'll need to create the relation entry first, then grab the ID of that entry and relate it to your next entry by simply assigning your relationsship field with it like this **$entry->getContent()->relationshipField = ID_FROM_PREVIOUS_ENTRY**
naboovalley
CC BY-SA 3.0
2015-02-03T14:53:23.857Z
2015-02-03T14:53:23.857Z
Aaron Berkowitz
<p>aberkie's answer is spot on. I just spent the last couple days doing exactly this — importing data from a non-craft database — so thought I would share some additional tips and files that helped. I also used 'PDO' to connect to the database instead of the 'Yii' connection method, but use whatever you like.</p>

<ul>
<li>Create your plugin called 'ImportPlugin' (or whatever) with a main plugin file ('import/ImportPlugin.php') and a services file ('import/services/ImportService.php').</li>
<li>Recommend installing a plugin called '<a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;ved=0CCIQFjAA&amp;url=https%3A%2F%2Fgithub.com%2Fam-impact%2Famcommand&amp;ei=VwvRVJq7LavdsATYvYGACg&amp;usg=AFQjCNFcGAskzUa5bZsiRnQeCXSbSWgzEw&amp;sig2=vn1Tr5SSu9fN5JE3pWAiFg&amp;bvm=bv.85076809,d.cWc" rel="nofollow">amcommand</a>' which does two things that are really helpful: 1) it creates a command palette with the option to 'delete all data' from a section, so that you can easily try again if something isn't quite right the first time (which it won't be); 2) it lets you define your own commands, by writing a few simple lines in your plugin file, so you can easily trigger your import service methods.</li>
<li>Open up your craft database and old database in Sequel Pro for reference.</li>
<li>Open up your 'craft.log', 'php_errors.log' and 'import.log' in console windows using <code>tail -f /path/to/craft/runtime/logs/logfile.php</code> for monitoring ('import.log' will be created automatically the first time you use it).</li>
<li>Recommend working on one section at a time, and backing up your craft database after each successfully import.</li>
</ul>

<p>In craft/plugins/import/ImportPlugin.php:</p>

<pre><code>&lt;?php
namespace Craft;

class ImportPlugin extends BasePlugin
{

    public function getName()
    {
        return 'Import';
    }

    public function getVersion()
    {
        return '0.1';
    }

    public function getDeveloper()
    {
        return craft()-&gt;getSiteName();
    }

    public function getDeveloperUrl()
    {
        return 'http://domain.com';
    }

    public function hasCpSection()
    {
        return false;
    }

    public function init()
    {
        parent::init();

        /*
         * This will call your import service method directly when loading
         * any craft template or viewing any page in the CP.
         * Useful for testing your output using `var_dump($vars)`.
         * Not so good for importing — because it may get called more than once.
         * Uncomment if needed.
         */
        //craft()-&gt;import-&gt;importRecords();

    }

    // Add custom commands to the 'amcommand' palette plugin
    public function addCommands() {
        $commands = array(

            array(
                'name' =&gt; 'Import Records',
                'type' =&gt; 'Custom',
                'call' =&gt; 'importRecords',
                'service' =&gt; 'import'
            ),
            // add more commands as needed

        );
        return $commands;
    }

}
</code></pre>

<p>In 'craft/plugins/import/services/ImportService.php' (Every case is different; this is just the process I happened to need. Use aberkie's solution if that is simpler):</p>

<pre><code>&lt;?php
namespace Craft;

class ImportService extends BaseApplicationComponent
{

    public function importRecords()
    {   
        $username = 'username';
        $password = 'password';

        try {
            $db = new \PDO('mysql:host=localhost;dbname=old_database;charset=utf8', $username, $password);
            $db-&gt;setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e-&gt;getMessage();
        }

        // Write query as needed (in this example I needed to join content from multiple tables)
        $query = 
            "SELECT a.id, b.id, b.tableA_id, c.tableB_id, a.field1, a.field2, b.field3, b.field4, c.field5, c.field6, c.field7
            FROM table_A a
            LEFT JOIN (table_B b, table_C c)
            ON (a.id = b.tableA_id AND b.id=c.tableB_id)
            ORDER BY a.id
            ";

        $result = $db-&gt;query($query);

        // reformat results for craft
        $records = [];

        foreach($result as $row)
        {
            /* Because of the sql table join I have more than one row
             * with the same id, so don't recreate the record if it 
             * already exists. Arbitrarily using row['id'] as key to join rows.
             */ 
            if (!array_key_exists($row['id'])
            {
                // map data
                $records[$row['id']] = array(
                    'craftfield1'   =&gt; $row['field1'],
                    'craftfield2'   =&gt; $row['field2'],
                    'craftfield3'   =&gt; [],
                );
            }

            /* if you need to combine data from multiple rows
             * into a single field in craft for some reason you can do it here.
             * (i.e. pushing content into a single craft table field)
             */

            array_push( $records[$row['id']]['craftfield3'] , array("col1" =&gt; $row['field3'], "col2" =&gt; $row['field4']) );

        }

        // create your craft entries
        foreach($records as $record) {

            $entry = new EntryModel();
            $entry-&gt;sectionId   = 1; // Use 'id' from 'craft_sections' table
            $entry-&gt;typeId      = 1; // Use 'id' from 'craft_entrytypes' table
            $entry-&gt;authorId    = 1; // Use 'id' from 'craft_users' table
            $entry-&gt;enabled     = true;

            $entry-&gt;getContent()-&gt;setAttributes($record);

            // Save entry
            $success = craft()-&gt;entries-&gt;saveEntry($entry);

            if (!$success)
            {
                $errors = $entry-&gt;getErrors();
                foreach ($errors as $error) {
                    ImportPlugin::log('Error:'.$error[0], LogLevel::Error);
                }
            }
            else
            {
                ImportPlugin::log('Successfully saved entry "'.$entry-&gt;id.'"', LogLevel::Info);
            };

            /* Print $records for debugging if needed.
             * Note: Will only work if calling this service method directly from
             * plugin's 'init' function, otherwise this will be a background process.
             */ 
            //var_dump($record);
            //print_r($record);
            //echo "&lt;br&gt;&lt;br&gt;";
        }

    }
}
</code></pre>

CC BY-SA 3.0
2015-02-03T18:41:42.893Z
2015-02-03T18:41:42.893Z
Douglas McDonald
<p>You might want to consider a CSV import as well.  You could export the data out of the db using something like phpmyadmin's export to csv and then import the content back into Craft using the indispensable  <a href="https://github.com/boboldehampsink/import" rel="nofollow">import plugin</a> by Bob Olde Hampsink to do the dirty work—it'll handle things like which author and mapping the fields and channels to the right places.</p>

<p>Obviously this will only work on a dump-by-dump case; if you need it continually updated, then writing your own might be the way to go.</p>

CC BY-SA 3.0
2015-02-03T18:40:07.160Z
2015-02-03T18:40:07.160Z
RitterKnight
<p>It's not just the <code>craft_content</code> table that you'll need to worry about because entry data is stored in multiple tables.</p>

<p>You're going to be better off using an existing import plugin or writing your own custom plugin that interacts with Craft's services... specifically <code>craft()-&gt;entries-&gt;saveEntry()</code>.</p>

<p>See <a href="https://craftcms.stackexchange.com/questions/5/how-do-i-import-data-into-craft">here</a> for more info.</p>

CC BY-SA 3.0
2015-02-03T15:06:28.500Z
That's what I feared. It's my first venture with Craft so I thin existing plugins would be a safer bet than rolling my own at this point.
Dr_Codswallop
CC BY-SA 3.0
2015-02-03T14:15:14.907Z
2015-02-03T14:15:14.907Z
Brad Bell
<p>Is it possible to populate the Craft content database table with entries from a non-craft database (which isn't a live database, it's a local copy). I've set up my channels etc for the incoming data which corresponds to the data from my other db.</p>

<database>
Populating craft database from non-craft data
# Populating craft database from non-craft data

(Asked by: username_0 on 2015-02-03)

Is it possible to populate the Craft content database table with entries from a non-craft database (which isn't a live database, it's a local copy). I've set up my channels etc for the incoming data which corresponds to the data from my other db.

**Tags:** database


---

## 4 answers

### Answer by username_1 on 2015-02-03. Score: 5

Brad is absolutely correct. Better off trying for an existing plugin (we have one in the works over here for very robust Wordpress migrating!!!), but here are a few steps to get you started:
Move the non-craft database tables over to a staging server with your craft tables, and rename them with a craft_ prefix (or whatever you have set as your prefix in config). 
Query for the entries
$query = craft()->db->createCommand()
->select('*')
->from('your-non-craft-post-table')
->where('any conditions')
->queryAll();

Loop through the query results, creating new Entry Models and assigning columns to your fields.
//Go through each $query result
foreach($query as $old_entry){
    $entry = new EntryModel();
    $entry->sectionId = your_craft_section_id;
    $entry->authorId = your_craft_user_id;
    $entry->postDate = $old_entry['old_post_date_column'];
    $entry->enabled = true;

    //This is the fun part - mapping content to your custom fields
    $entry->getContent()->title = $old_entry['old_title_column'];
    $entry->getContent()->yourCustomFieldHandle = $old_entry['column_to_map_to_custom_field'];

    //Use the Entries service to save the new entry
    $success = craft()->entries->saveEntry($entry);
}

Obviously there is more to it than that...mapping user accounts, categories, tags, assets, etc. But hopefully this will help you get started!

> **Comments:**
> **username_2**: Side note: If you have relations you'll need to create the relation entry first, then grab the ID of that entry and relate it to your next entry by simply assigning your relationsship field with it like this **$entry->getContent()->relationshipField = ID_FROM_PREVIOUS_ENTRY**  

---

### Answer by username_3 on 2015-02-03. Score: 3

aberkie's answer is spot on. I just spent the last couple days doing exactly this — importing data from a non-craft database — so thought I would share some additional tips and files that helped. I also used 'PDO' to connect to the database instead of the 'Yii' connection method, but use whatever you like.

Create your plugin called 'ImportPlugin' (or whatever) with a main plugin file ('import/ImportPlugin.php') and a services file ('import/services/ImportService.php').
Recommend installing a plugin called 'amcommand' which does two things that are really helpful: 1) it creates a command palette with the option to 'delete all data' from a section, so that you can easily try again if something isn't quite right the first time (which it won't be); 2) it lets you define your own commands, by writing a few simple lines in your plugin file, so you can easily trigger your import service methods.
Open up your craft database and old database in Sequel Pro for reference.
Open up your 'craft.log', 'php_errors.log' and 'import.log' in console windows using tail -f /path/to/craft/runtime/logs/logfile.php for monitoring ('import.log' will be created automatically the first time you use it).
Recommend working on one section at a time, and backing up your craft database after each successfully import.

In craft/plugins/import/ImportPlugin.php:
getSiteName();
    }

    public function getDeveloperUrl()
    {
        return 'http://domain.com';
    }

    public function hasCpSection()
    {
        return false;
    }

    public function init()
    {
        parent::init();

        /*
         * This will call your import service method directly when loading
         * any craft template or viewing any page in the CP.
         * Useful for testing your output using `var_dump($vars)`.
         * Not so good for importing — because it may get called more than once.
         * Uncomment if needed.
         */
        //craft()->import->importRecords();

    }

    // Add custom commands to the 'amcommand' palette plugin
    public function addCommands() {
        $commands = array(

            array(
                'name' => 'Import Records',
                'type' => 'Custom',
                'call' => 'importRecords',
                'service' => 'import'
            ),
            // add more commands as needed

        );
        return $commands;
    }

}

In 'craft/plugins/import/services/ImportService.php' (Every case is different; this is just the process I happened to need. Use aberkie's solution if that is simpler):
setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

        // Write query as needed (in this example I needed to join content from multiple tables)
        $query = 
            "SELECT a.id, b.id, b.tableA_id, c.tableB_id, a.field1, a.field2, b.field3, b.field4, c.field5, c.field6, c.field7
            FROM table_A a
            LEFT JOIN (table_B b, table_C c)
            ON (a.id = b.tableA_id AND b.id=c.tableB_id)
            ORDER BY a.id
            ";

        $result = $db->query($query);

        // reformat results for craft
        $records = [];

        foreach($result as $row)
        {
            /* Because of the sql table join I have more than one row
             * with the same id, so don't recreate the record if it 
             * already exists. Arbitrarily using row['id'] as key to join rows.
             */ 
            if (!array_key_exists($row['id'])
            {
                // map data
                $records[$row['id']] = array(
                    'craftfield1'   => $row['field1'],
                    'craftfield2'   => $row['field2'],
                    'craftfield3'   => [],
                );
            }

            /* if you need to combine data from multiple rows
             * into a single field in craft for some reason you can do it here.
             * (i.e. pushing content into a single craft table field)
             */

            array_push( $records[$row['id']]['craftfield3'] , array("col1" => $row['field3'], "col2" => $row['field4']) );

        }

        // create your craft entries
        foreach($records as $record) {

            $entry = new EntryModel();
            $entry->sectionId   = 1; // Use 'id' from 'craft_sections' table
            $entry->typeId      = 1; // Use 'id' from 'craft_entrytypes' table
            $entry->authorId    = 1; // Use 'id' from 'craft_users' table
            $entry->enabled     = true;

            $entry->getContent()->setAttributes($record);

            // Save entry
            $success = craft()->entries->saveEntry($entry);

            if (!$success)
            {
                $errors = $entry->getErrors();
                foreach ($errors as $error) {
                    ImportPlugin::log('Error:'.$error[0], LogLevel::Error);
                }
            }
            else
            {
                ImportPlugin::log('Successfully saved entry "'.$entry->id.'"', LogLevel::Info);
            };

            /* Print $records for debugging if needed.
             * Note: Will only work if calling this service method directly from
             * plugin's 'init' function, otherwise this will be a background process.
             */ 
            //var_dump($record);
            //print_r($record);
            //echo "";
        }

    }
}


---

### Answer by username_4 on 2015-02-03. Score: 3

You might want to consider a CSV import as well. You could export the data out of the db using something like phpmyadmin's export to csv and then import the content back into Craft using the indispensable [import plugin](https://github.com/boboldehampsink/import) by Bob Olde Hampsink to do the dirty work—it'll handle things like which author and mapping the fields and channels to the right places.

Obviously this will only work on a dump-by-dump case; if you need it continually updated, then writing your own might be the way to go.


---

### Answer by username_5 on 2015-02-03. Score: 1

It's not just the `craft_content` table that you'll need to worry about because entry data is stored in multiple tables.

You're going to be better off using an existing import plugin or writing your own custom plugin that interacts with Craft's services... specifically `craft()->entries->saveEntry()`.

See [here](https://craftcms.stackexchange.com/questions/5/how-do-i-import-data-into-craft) for more info.

> **Comments:**
> **username_0**: That's what I feared. It's my first venture with Craft so I thin existing plugins would be a safer bet than rolling my own at this point.  

---

