Write database queries in Magento custom module - mysql

I created a custom module in my Magento. This is working good. My module's name is mymodule.
Mymodule.php
class Myshop_Mymodule_Block_Mymodule extends Mage_Core_Block_Template
{
public function myfunction()
{
return "Hello User";
}
}
The path of the Mymodule.php file is C:\wamp\www\magento\app\code\local\Myshop\Mymodule\Block.
Now I want to display some data from database. For example I would like to display the admin's email id. How can I display this??
I tried like this.
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
//database write adapter
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $read->fetchAll("select email from admin_user where user_id= 1");
var_dump($result);
I write these lines in Mymodule.php inside myfunction. But nothing displayed(display only "Hello User").
So my question is how to display or write database queries in magento custom module.
Please someone help me..Any help is really appreciable..

We generally avoid using adapters when magento by default provides models for the basic tables. In your case, you can fetch the admin details using following :
<?php
$userDetails = Mage::getModel('admin/user')->load(1);
//where 1 is your admin user id
echo $userDetails->getEmail();
?>
Hence, your function can be modified as :
<?php
class Myshop_Mymodule_Block_Mymodule extends Mage_Core_Block_Template
{
public function myfunction()
{
$userDetails = Mage::getModel('admin/user')->load(1);
return $userDetails->getEmail();
}
}

You can get data from database in magento as
$collection = Mage::getModel("mumodule/mymodule")->getCollection();
foreach($collection as $data){
..Your Code ..
}

Related

Need to change timezone dynamically for existing project

There is an existing project only for one country. But for now, it should be used for multiple countries. So I need some place to change timezones. I decided to update & insert in only London/Sydney timezone. I need to change the timezone for all select queries. I just tried with middlewares, but I could not achieve it. Please give your suggestions.
Linux server, MySQL, Laravel, Vagrant
namespace App\Http\v2018_06_12\Middleware;
use App;
use App\Order;
use Closure;
class LocaleMiddleware
{
public function handle($request, Closure $next, $guard = null)
{
$locale = ($request->hasHeader('locale')) ? $request->header('locale') : 'uk';
$timezone = env('APP_TIMEZONE');
if ('aus' == $locale) {
$timezone = 'Australia/Sydney';
}
config(['app.timezone' => $timezone]);
date_default_timezone_set($timezone);
print_r(Order::select('delivery_time')->orderBy('id', 'DESC')->first()->toArray());
return $next($request);
}
}

How to upload a file for an existing user in the database and create a folder for them in laravel 5.4

I am developing a document archive system and i want the user to be able to upload a file to a specific folder that should be linked to an existing user in the database. what do i need to do?
This is for xampp server running PHP 7.0.3 and with Laravel 5.4. I am able to upload a file but it has no owner.
No code to display.
I expect to be able to search for a user according to their name and retrieve their files
You may want to use one to many relationships for this.
First create a document model and migration with below command.
php artisan make:model Document -m // -m option for migration file
Configure user and document models for one to many relation
User Model
public function documents()
{
return $this->hasMany('App\Document');
}
Document Model
public function user()
{
return $this->belongsTo('App\User');
}
create_documents_table Migration
Edit migration file and add name, path,type etc.. columns..
public function up()
{
Schema::create('documents', function(Blueprint $table)
{
$table->increments('id');
$table->string("name");
$table->string("path");
$table->string("type");
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
then run php artisan:migrate command.
Done! So let upload a file..
public function upload(Request $request){
// get file from request
$file = $request->file("document");
// get username for file path (if user directory doesn't exist, Storage gonna create it)
$username = $request->user()->username;
// make file name unique
$file_name = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$realName = str_slug($file_name); // it makes seo frendly
$extension = $file->getClientOriginalExtension();
$newFileName = $username."/".$realName . "-" . time() . "." . $extension;
// store document on db (make sure these columns fillable on model or it throws error)
$request->user()->documents()->create([
"name"=>$file_name
"path"=>$newFileName
"type"=>"document"
]);
// move uploaded file
Storage::disk("locale")->put($newFileName,file_get_contents($file));
}
For more further I strongly to suggest you to read documents. It makes you to understand how eloquent handle with the relational queries
File uploads should not be handled by folders. When you upload a file, give it a unique name. Save this name in a database files for example, where you have columns user_id, and file_name. Then when you want to get all files for a specific user you just send query to the database. Laravel already has most of this done and it looks like this:
$uploadedImage = $request->image->store('images');
This will return something like this:
"images/7UmX8yrOs2NYhpadt4Eacq4TFtpPGUCw6VTRJhfn.img"
then you do something like this:
$image = new Image();
$image->user_id = $user_id;
$image->path = $uploadedImage();
$image->save();
If you want to give the name for the image yourself you can use storeAs instead of store method like this:
$uploadedImage = $request->image->storeAs('images', $filename);

How to conditionally use different database in CodeIgniter

Here is my scenario.
A user will login to the system. Based on the username, I need to set the database in codeigniter configuration.
I know that the line $this->load->database() in each model loads the default database.
So, after checking the username in session(assuming that the user has successfully logged in), how can I dynamically load a database?
Below is something that I am looking for:
if(username == 'foo'){
$this->load->database('database_name');
}
An example of a model function that I have written is as follows:
public function check_valid_login($username, $password){
$this->db->from('tbl_user_details');
$this->db->where('email_address', $username);
$this->db->where('password', md5($password));
$query = $this->db->get();
$rowcount = $query->num_rows();
return $rowcount ;
}
On selecting the database, how can I still use statements like $this->db->from('tbl_user_details'); and so on. i.e., I want to use $this->db itself. Is it possible to do that?
I think I found a solution.
This is the strategy that I followed: When the user tries to login, a session variable $_SESSION['dynamic_db_username'] is set with the username that is provided by the user.
The following logic is used for selecting the database dynamically. The below code is written in config/database.php
/*Dynamic database selection - begins*/
if(!empty($_SESSION['dynamic_db_username'])){
$dynamic_db_username = $_SESSION['dynamic_db_username'];
if($dynamic_db_username == 'sample#domain.com')
{
$db['default']['database'] = 'database_1';
}
elseif($dynamic_db_username == 'sample2#domain.com')
{
$db['default']['database'] = 'database_2';
}
else
{
$db['default']['database'] = 'database_1';
}
}
else
{
$db['default']['database'] = 'database_1';
}
/*End*/
Kindly review this strategy and please let me know if this is right.
in the config folder there was a file named autoload.php
open the file
find first this code below
$autoload['libraries'] = array('');
you have to put "database" in the array , changed code will be like
$autoload['libraries'] = array('database');
after that you can use your database anytime and anywhere without loading it manually .

Symfony2 execute SQL file in Doctrine Fixtures Load

I'm migrating an old web app based on SQL Server and ASP to Symfony2 and MySQL. I made some queries and export old data to individual SQL files.
How can I execute thoses files in my fixtures, when I run the command
$php app/console doctrine:fixtures:load
Now I have some fixtures that works directly with Doctrine ORM and entities, but I have a lot of data to import.
I find a good solution. I didn't find an exec method in class ObjectManager, so... this work very well for me.
public function load(ObjectManager $manager)
{
// Bundle to manage file and directories
$finder = new Finder();
$finder->in('web/sql');
$finder->name('categories.sql');
foreach( $finder as $file ){
$content = $file->getContents();
$stmt = $this->container->get('doctrine.orm.entity_manager')->getConnection()->prepare($content);
$stmt->execute();
}
}
In this solution your fixture class has to implement the ContainerAwareInterface with the method
public function setContainer( ContainerInterface $container = null )
{
$this->container = $container;
}
You can load the file contents as a string, and execute native SQL using the EntityManager:
class SQLFixtures extends AbstractFixture implements OrderedFixtureInterface
{
$filename = '/path/to/sql/file.sql';
public function load(ObjectManager $manager) {
$sql = file_get_contents($filename); // Read file contents
$manager->getConnection()->exec($sql); // Execute native SQL
$manager->flush();
}
public function getOrder() {
return 99; // Order in which this fixture will be executed
}
}
Answer for Zend Framework 2.5.3 using Doctrine Data-Fixtures.
Not sure if this applies to the given answers, but they are trying a bit too hard. If you inspect the given $manager object, you'll find that it already is the EntityManager (of interface ObjectManager) (at least, in ZF2). As such you're able to get the Connection directly and it's possible to execute without using $this->container->get('doctrine.orm.entity_manager')
Below a snippet which I use for creating the first user "system", with a createdBy FK reference to itself.
public function load(ObjectManager $manager)
{
$sql = 'INSERT INTO users (
id, username, email, display_name, `password`, created_by)
VALUES (:id, :username, :email, :display_name, :password, :created_by)';
$password = $this->createSuperDuperEncryptedPassword();
// $manager === `EntityManager|ObjectManager`, `->getConnection()` is available
$stmt = $manager->getConnection()->prepare($sql);
$stmt->bindValue(':id', 1);
$stmt->bindValue(':username', 'system');
$stmt->bindValue(':email', 'system#system.test');
$stmt->bindValue(':display_name', 'system');
$stmt->bindValue(':password', password );
$stmt->bindValue(':created_by', 1); // Self reference
$stmt->execute();
}

Json call in joomla 2.5 component

I'm making a joomla 2.5 component and i trying to set in model or controller (what's the most appropriate ?) a json response of my DB request (for later get the json with angularJS).
Here's my model (with DB response):
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modelList' );
class MediastoreModelList extends JModelList
{
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id, type, designation', 'marque', 'prix');
$query->from('produits');
return $query;
}
}
My empty controller:
<?PHP
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class MediastoreController extends JController
{
}
My view
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
jimport( 'joomla.application.component.view' );
class MediastoreViewList extends JView
{
function display($tpl = null)
{
$this->items = $this->get('items');
parent::display($tpl);
}
}
and my template
<?php
defined('_JEXEC') or die('Restricted access');
JHTML::script('media/com_mediastore/js/angular.min.js');
JHTML::script('media/com_mediastore/js/app.js');
?>
<?php
echo $this->items;
?>
<div class="content">
<p>Nothing</p>
</div>
How can i do that ?
Thanks a lot,
Antoine
Bit late .....
Hi I am working on something similar.
In your views (sitepart) add an other file called view.raw.php.
You can browse to this file by appending 'format=raw' at the end of the url.
For example: if your component view page in the browser is 'http://test.com/test( IF SEF is on ) then after appending th url shoul be like this
http://test.com/test?format=raw and in case SEF is not on the use & instead of ?
You can use this URL in the angularjs for http.get service.
In view.raw.php file make sure you just echo the results rather than parent::display($tpl);.
This did work for me.
PS: I am using angualrjs too but want to use the component with many menu items and the url keeps changing so am stuck on that part.
Hope this solves your issue.
Regards,
Jai