Skip to content

Instantly share code, notes, and snippets.

@steve-ross
Last active August 29, 2015 13:58
Show Gist options
  • Save steve-ross/9956896 to your computer and use it in GitHub Desktop.
Save steve-ross/9956896 to your computer and use it in GitHub Desktop.
Mage, getting standard db connection
// instead of the following:
// db variables
$dsn = 'the dsn hard coded';
$username = 'username hard coded';
$password = 'password hard coded';
// try to connect to the db
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
die('Could not connec to to the database.<br />');
}
// create the statement handle
$sth = $db->prepare("INSERT INTO newsletter_codes (email_address, discount_code) values (:email_address, :coupon_code)");
// bind the parameters
$sth->bindParam(':email_address', $_GET['email']);
$sth->bindParam(':coupon_code', $coupon_code);
// execute!
$sth->execute();
// You can simply do the following
$db = Mage::getSingleton('core/resource')->getConnection('core_write');
$query = "INSERT INTO newsletter_codes (email_address, discount_code) values (:email_address, :coupon_code)";
$params = array(
'email_address' => $_GET['email'],
'coupon_code' => $coupon_code
);
$db->query($query, $params);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment