MySQL resource in Zend Framework - mysql

I'm starting a new project built on Zend Framework. I know all about controllers, layouts and views. But I don't know how to add a MySQL resource.
Basically, I would like to have some model classes with getters and setters and for each, a resource class witch would handle MySQL queries. These resources classes need access to a DB class which performs the actual queries. The configuration for the DB would have to be in a separate file somewhere as either XML data, .ini or PHP array.
How can I obtain that? Where should I put each the files (right now, I have the default Zend directory structure)?

You dont need to create an instace of connection to database ,Zend does it automatically..just add these following to your config file
resources.db.adapter = "PDO_MYSQL"
resources.db.isDefaultTableAdapter = true;
resources.db.params.host = "yourserver"
resources.db.params.username = "username"
resources.db.params.password = "pwd"
resources.db.params.dbname = "dbname"

you can use it later
$DB = Zend_Db_Table_Abstract::getDefaultAdapter();

Zend comes with a set of DB classes that you can use. Documentation is here: http://framework.zend.com/manual/en/zend.db.html Before asking questions like this please do a bit of Googling.

[general]
db.adapter = PDO_MYSQL
db.params.host = server
db.params.username = username
db.params.password = password
db.params.dbname = dbname
$config = new Zend_Config_Ini(ROOT_DIR.'/application/config.ini', 'general');
$DB = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($DB);
$DB = Zend_Db_Table_Abstract::getDefaultAdapter();

Related

How can I query to database from zend framework view (phtml)?

I need to access database from phtml (view) in zend. how can i do that?
$stmt = $db->query('SELECT * FROM mcommerce_cart');
Well, you should not do this (it's bad practice). Recommend way is to access DB via models. You can pass data to view from Controller, Zend_View_Helper or (also no so recommeneded) via direct call to model.
But if you really want to access DB in View than you can get Default Adapter by calling $db = Zend_Db_Table::getDefaultAdapter();

How do I use MySQL for dynamic doc root with Nginx?

I've been trying to find out a way to first capture environment variable HOSTNAME and then use a MySQL query to fetch and return back to the Nginx conf the document root for our vhosts. We use them for dynamic doc roots currently in Apache but are migrating to Nginx.
example nginx.conf (might look something like this):
server {
listen 80;
# grab Environment variable HOSTNAME
$hostname= ENV(HOSTNAME);
# execute mysql query
$doc_root = mysql(select docroot from table where host = '$hostname' );
# set document root
root /var/www/$doc_root;
.....
I was exploring using Lua and https://github.com/openresty/lua-resty-mysql but have been unable to figure out how this could be done to capture HOSTNAME and mysql query as a variable and return the results back.
Thanks for your help. It didn't work for me, but after a lot of work, I finally got something working. This is for someone else if they ever need it
it turns out $http_host is already defined globally in nginx - so that was fixed.
set $httphost $http_host; # create and initialize var
set $docroot "";
# begin LUA scripting
rewrite_by_lua '
-- make sure http host is defined
if not ngx.var.httphost then
ngx.log(ngx.ERR,"ERROR - no httphost defined")
return
end
-- begin mysql
local mysql = require "resty.mysql"
local db, err = mysql:new()
db:set_timeout(1000) -- 1 sec
local ok, err, errno, sqlstate = db:connect
{
host = "127.0.0.1",
port = 3306,
database = "db",
user = "user",
password = "password",
max_packet_size = 1024 * 1024
}
if not ok then
ngx.log(ngx.ERR,"MySQL failed to connect: ", err, ": ", errno, " ", sqlstate)
return
end
-- prevent injection attack
local hname = ngx.unescape_uri(client)
local quoted_name = ngx.quote_sql_str(hname)
local sql = "select docroot from users where customer =" .. quoted_name
result,err,errno,sqlstate = db:query(sql,1)
if not result then
ngx.log(ngx.ERR,"MySQL bad result: ", err, ": ", errno, ": ", sqlstate, ".")
return
end
if not result[1].docroot then
ngx.log(ngx.ERR,"MySQL ERROR - no docroot was returned")
return
end
ngx.var.docroot = result[1].docroot
';
# now we can set the docroot for this host
root /var/www/$docroot;
First of all, using a database for doing basic routing does not sound like a very good idea - I would recommend having the results cached in memory and maybe refreshing them periodically from the database.
Second, the basic Nginx config file will get you only so far - in order to get more advanced functionality you will need to use a scripting language (like Lua) on top of it. One of the things this allows you is reading environment variables. I wrote about how to do it here:
https://docs.apitools.com/blog/2014/07/02/using-environment-variables-in-nginx-conf.html
The usual way to get Lua working on Nginx is using Openresty, a version of Nginx which comes with several modules pre-installed, including the Lua one. You can add lua-resty-mysql to the mix, and then do everything you want directly from Lua. I have never used lua-resty-mysql so I can't code that for you. If you are set on using Mysql, you will have to study its docs. Give a look at Redis while you are at it, it might be a better fit than Mysql.

How to create another db connection with codeigniter

I need to connect to another mysql database I am doing following
$dsn = "{$dbdriver}://$vars[username]:$vars[password]#$vars[hostname]/$vars[database]";
$db2 = $this->EE->load->database($dsn, true);
$res = $db2->from('categories')->get()->result_array();
But I get error message Fatal error: Call to a member function result_array() on a non-object
That is third party script so db connection already made early. Then that script should connect to another db but 1st db connection already created
$dsn contains correct data. Why I get this error?
Thanks
Write parameters of 2nd database on confid/database.php also.
$db['second_db']['hostname'] = 'localhost';
$db['second_db']['username'] = 'foo';
...
And
$db2 = $this->EE->load->database('second_db', true);
I have figured it out. The query should contains additional param db_debug=1 so the dsn string should look like
$dsn = "mysql://$vars[username]:$vars[password]#$vars[hostname]/$vars[database]?db_debug=1";
If you read the codeigniter user guide you will find the answers easily. The heading is
Connecting to Multiple Databases
https://www.codeigniter.com/user_guide/database/connecting.html

CodeIgniter: how to configure to connect to a different DB?

Currently, I have my database configuration something like this:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "my_username";
$db['default']['password'] = "my_password";
I actually want to connect to a different MySQL database hosted on a different server. Where would I find the hostname I need to use? Is there anything else I need to do besides changing the hostname?
Make an array of arrays, and always explicitly index them as needed:
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "foo";
$db['default']['password'] = bar";
$db['default']['database'] = "blablabla";
$db['development']['hostname'] = "localhost";
$db['development']['username'] = "boo";
$db['development']['password'] = "par";
$db['development']['database'] = "blablabladev";
$this->dbdev = $this->load->database('development', TRUE);
Usually, you'll be able to get this information from the same place you created the database. So if you used a control panel on your web host to create the database, it's likely you will be able to find the address by looking around the control panel's MySql section.
Some web hosts don't allow remote access to the database either, so be wary of that.
To answer your second question, yes, you will likely have to change the username and password, the new values should also be found in the area where you created the database.
Apologies if this is a very generic answer.
$db['default']['hostname'] = "new.host.name.com";
Also make sure that mysql on your new.host.name.com will accept external connection, by providing your localhost IP

Set MySQL session variable - timezone - using Doctrine 1.2 and Zend Framework

Got a Zend Framework web application using Doctrine 1.2 connecting to a MYSQL 5.1 server.
Most data needs to be entered and displayed in local timezone. So following the advice here, I'd like (I think) to set PHP and MySQL to use UTC and then I'll handle the conversion to local time for display and to UTC prior to insert/update. [If this is totally goofy, I'm happy to to hear a better approach.]
So, how do I tell Doctrine to set the MySQL session to UTC? Essentially, how do I tell Doctrine to issue the MySQL command SET SESSION time_zone = 'UTC'; when it opens the connection?
Thanks in advance!
It appears that this can be done by attaching to the Doctrine_Connection object an Doctrine_EventListener with a postConnect() method.
Doctrine ORM for PHP - Creating a New Listener
Something like:
class Kwis_Doctrine_EventListener_Timezone extends Doctrine_EventListener
{
protected $_timezone;
public function __construct($timezone = 'UTC')
{
$timezone = (string) $timezone;
$this->_timezone = $timezone;
}
public function postConnect(Doctrine_Event $event)
{
$conn = $event->getInvoker();
$conn->execute(sprintf("SET session time_zone = '%s';", $this->_timezone));
}
}
[Using sprintf() here is probably amateurish, but I couldn't figure out how to do a proper parameter bind. (embarrassed smiley).]
Then in my app's Bootstrap.php, I have something like:
protected function _initDoctrine()
{
// various operations relating to autoloading
// ..
$doctrineConfig = $this->getOption('doctrine');
$manager = Doctrine_Manager::getInstance();
// various boostrapping operations on the manager
// ..
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'], 'doctrine');
// various boostrapping operations on the connection
// ..
// Here's the good stuff: Add the EventListener
$conn->addListener(new Kwis_Doctrine_EventListener_Timezone());
return $conn;
}
[One slightly off-topic note: on my local development machine, I kept running into a MySQL error in which no timezone I entered seemed to be accepted. Turns out that the standard MySQL install creates all the timezone tables in the mysql database, but doesn't actually populate them; you need to populate them separately. More info at MySQL site.]