Stuff & Nonsense

Access magento database outside magento

Just a quick note, sometimes you need to access the magento database from a script, but don’t want the overhead of loading the whole magento framework….. Here’s a little snippet of code that  grabs the database details from the magento xml config, so you don’t have to store them in your script:

<?php
 class db {

 private $data = null;


 public function __construct(){
     $xml=simplexml_load_file(realpath(dirname(__FILE__))."/../../app/etc/local.xml");

     $host = (string) $xml->global->resources->default_setup->connection->host;
     $db = (string) $xml->global->resources->default_setup->connection->dbname;
     $user =(string) $xml->global->resources->default_setup->connection->username;
     $pass = (string) $xml->global->resources->default_setup->connection->password;
     $charset = 'utf8mb4';

     $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
     $opt = [
         PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
         PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
         PDO::ATTR_EMULATE_PREPARES => false,
     ];
     $this->data = new PDO($dsn, $user, $pass, $opt);
 }

 public function query($sql){
    return $this->data->query($sql)->fetchAll(PDO::FETCH_ASSOC);
 }

 }

 ?>

Save it somewhere like /magento_root/scripts/include/db.php and use it like this:
 

<?php

require "include/db.php"
$db = new db();

$results = $db->query('select * from cataloginventory_stock_item');

?>

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.