How to run Custom Mysql Query in Magento

Magento uses Zend framework in very standered manner . It uses singleton methodology to access database.Like many other standered frameworks Magento also uses the concept of ORM (Object Relation Model) approach. To access the database Magento uses resource model where each magento model is divided into two categories
i) Active Record type
ii) EAV (Entity Attribute Value) Model
With this resource model we can manipulate the data from our database.

But still if we want to run our own custom mysql query Magento provides a way to do this also. Here are the way to do

/*Because we need to read the data then we will get connection for core_read.
Suppose you need to insert some data into database then you need to take core_write.
$db = Mage::getSingleton('core/resource')->getConnection('core_read');
//Write your mysql query here
$result = $db->query("SELECT * FROM customerhistory WHERE customer_id = ".$customer->getId()." AND status <> 0 ORDER BY created_time DESC LIMIT 0,100");
//After running check whether data is available or not
if(!$result) {
echo 'No data found';
//Here we are fetching the data
while ($row = $result->fetch(PDO::FETCH_ASSOC))
echo $row["content"];

In the next blog we will see the standard way to receive data from database with Magento collection.

Related posts:

The following two tabs change content below.

Chandra Shekhar

GCP Architect
Chandra Shekhar Pandey is Google certified Cloud engineer, I am Magento2 Trained developer. Having huge experience in designing cloud solution. I have around 12 years of experience with world enterprise IT companies and fortune 500 clients. During my architecture design I am always caring about high availability, fast performance and resilient system. From the programmer background I have huge experience in LAMP stack as well. Throughout my carrier I have worked on Retail, E-Learning, Video... Read More about Chandra Shekhar

Latest posts by Chandra Shekhar (see all)