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();
Related
I'm creating a quick and dirty console controller to create fixtures from a database table.
I'd like to use a where clause to limit this - but would like to make the controller a little less dirty and prevent injections.
My current console command specification is:
db create fixture <table_name> [--where=]
The controller action has:
$tableName = $request->getParam('table_name');
$where = $request->getParam('where');
$queryString = "select * from `$tableName`";
if (!is_null($where)) {
$queryString .= " where $where";
}
$resultSet = $dbAdapter->query(
$queryString,
DbAdapter::QUERY_MODE_EXECUTE
);
Now, I know this is obviously wide open to SQL injection - as confirmed when I ran the following:
db create fixture hit_log --where="\`timestamp\` between '2015-01-20 00:00:00' and '2015-01-30 00:00:00'; delete from hit_log limit 1";
So, what would be a good strategy to fix this?
I'm thinking of JSON notation --where='{"timestamp":["between","2015-01-20","2015-02-30"]}' - but then I'll have to write a translator to handle different tests like "=", "LIKE", and "BETWEEN".
Edit:
I've put checks in the controller action to ensure it is a console only request, and will error out if a user somehow manages to route via the http router.
This then assumes that a developer is running the command, and would have access to the database anyway. I guess this is more trying to protect against error than malice.
I'm writing an application that has a functions.php file that a javascript file is accessing via Ajax. Currently I have each function connecting to the database, running queries, then closing the database. I know there has to be a more efficient way of doing this. I'd like to only input the database credentials once and then have all the functions use it. Whats the most efficient way to do this? I've read quite a few of the answers here on this topic but they're all different and I'm lost. Just point me in the right direction :)
Currently my functions are opening the database like this.
$db = new mysqli("hostname", "username", "password");
$db -> select_db("database name");
Or like this
mysql_connect("hostname", "username", "password");
mysql_select_db('database name') or die( "Unable to select database");
The simple answer is connection pooling. A connection pool is a pool of connections that are always connected to the database. You can set a high water mark and a low water mark for the number of connections.
When your application requests a connection from the pool it will then use one of the idle connections and reuse it. This is how you scale database connectivity.
You are using PHP so look at the following:
http://www.oracle.com/technetwork/topics/php/php-scalability-ha-twp-128842.pdf
http://php.net/manual/en/mysqlnd-ms.pooling.php
There is a lot of information around this on the net.
You can just check whether the database connection variable is already set:
if (!isset($db)) {
$db = new mysqli(...);
$db->select_db("database_name");
}
and similarly with mysql_connect (it returns a connection resource, so you can assign it to a variable, even though it's an optional argument to the other functions).
Another way is to use a function with a static variable:
function connect_db() {
static $db = new mysqli(...);
static $selected = $db->select_db("database_name");
return $db;
}
A third options is to connect to the database once at the beginning of the script, instead of in each function. Then either pass $db to each function, or access it with global $db;.
In cakephp I want to be able connect to a different database from one action on the site. The action determines which database and host to connect to. Using cakephp 1.3.
Ive seen where you can change the db connection in beforeFilter for a controller, but I want to be able handle this from the action, because that is where I find the database and/or host, that I need to connect to.
I can write my own SQL inside there. I don't need to go through models. Just want to do a simple add/update SQL statement.
You can easily configure more than one database connection to use in your app.
In config/database.php, create another variable for your database configuration, in addition to the existing $default:
var $otherDatabase = array(
'driver' => 'mysql',
// more settings...
);
Then, in your model, set $this->useDbConfig = 'otherDatabase' or in your controller $this->MyModel->useDbConfig = 'otherDatabase'. Any subsequent find()s will use the configured database.
Sorry, if this is a newbie question.
We're building an analytics application, with different components. The visualization and web app is in Django, backend connecting drivers are written using PHP, and various analytics are written in python (precomputed, django is only responsible for rendering).
All these components access and update the same database (mysql). The tables were created by Django ORM, but are updated by Python scripts (mysqldb) and PHP as required.
Are there any unseen downsides to this approach of mixing django ORM access and direct database access? For the python component, we could use ('from django.core.management import setup_environ'), but its more efficient to have direct control over SQL statements. Is there a better design approach that we should be aware of?
The only downside is we can think of, is the added complexity to future changes to the database/models.py, but that's something we can live with.
Thanks!
Answering this myself.
We have this working fine since several weeks. The only downside of course, is that if we make changes to models.py (using django ORM), we have to tweak PHP code by hand, which would be expected.
For authenticated users, the PHP code uses data from auth_user to authenticate incoming connections. The exact use of password + salt to generate hash is documented in other posts, see What is the format in which Django passwords are stored in the database?.
Edit: #Josh asked for the PHP snippet, here it is:
// ASSUMES YOU HAVE django username and password from web form POST request
// GET THE HASH + SALT FOR THIS USER
$query = "SELECT password FROM auth_user WHERE username = '$_POST[email]' LIMIT 1 ";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
list($algo,$salt,$pass) = explode('$',$row['password']);
// RE-HASH PASSWORD from POST request
$hash = sha1($salt . $_POST['password']);
$hash = "sha1$$salt$$hash";
// GET HASH FROM DATABASE TO COMPARE
$query = "SELECT username FROM auth_user WHERE password = '$hash' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
I've connected to a MySQL database using Perl DBI. I would like to find out which database I'm connected to.
I don't think I can use:
$dbh->{Name}
because I call USE new_database and $dbh->{Name} only reports the database that I initially connected to.
Is there any trick or do I need to keep track of the database name?
Try just executing the query
select DATABASE();
From what I could find, the DBH has access to the DSN that you initially connected with, but not after you made the change. (There's probably a better way to switch databases.)
$dbh->{Name} returns the db name from your db handle.
If you connected to another db after connected with your dbh, using mysql query "USE db_name", and you did not setup a new perl DBI db handle, of course, $dbh->{Name} will return the first you previously connected to... It's not spontaneic generation.
So to get the connected db name once the db handle is set up - for DBI mysql:
sub get_dbname {
my ($dbh) = #_;
my $connected_db = $dbh->{name};
$connected_db =~ s/^dbname=([^;].*);host.*$/$1/;
return $connected_db;
}
You can ask mysql:
($dbname) = (each %{$dbh->selectrow_hashref("show tables")}) =~ /^Tables_in_(.*)/;
Update: obviously select DATABASE() is a better way to do it :)
When you create a connection object it is for a certain database. In DBI's case anyway. I I don't believe doing the SQL USE database_name will affect your connection instance at all. Maybe there is a select_db (My DBI is rusty) function for the connection object or you'll have to create a new connection to the new database for the connection instance to properly report it.
FWIW - probably not much - DBD::Informix keeps track of the current database, which can change if you do operations such as CREATE DATABASE. The $dbh->{Name} attribute is specified by the DBI spec as the name used when the handle is established. Consequently, there is an Informix-specific attribute $dbh->{ix_DatabaseName} that provides the actual current database name. See: perldoc DBD::Informix.
You could consider requesting the maintainer(s) of DBD::MySQL add a similar attribute.