How to create another db connection with codeigniter - mysql

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

Related

Pass custom variables in MySQL connection

I am setting up a MySQL connection (in my case PDO but it shouldn't matter) in a REST API.
The REST API uses an internal authentication (username / password). There are multiple user groups accessing the REST API, e.g. customers, IT, backend, customer service. They all use the same MySQL connection in the end because they also use the same end points most of the time.
In the MySQL database I would like to save the user who is responsible for a change in a data set.
I would like to implement this on the MySQL layer through a trigger. So, I have to pass the user information from the REST API to this trigger somehow. There are some MySQL calls like CURRENT_USER() or status that allow to query for meta-information. My idea was to somehow pass additional information in the connection string to MySQL, so that I don't have to use different database users but I am still able to retrieve this information from within the trigger.
I have done some research and don't think it is possible, but since it would facilitate my task a lot, I still wanted to ask on SO if someone did know a solution for my problem.
I would set a session variable on connect.
Thanks to the comment from #Álvaro González for reminding me about running a command on PDO init.
The suggestion of adding data to a temp table isn't necessary. It's just as good to set one or more session variables, assuming you just need a few scalars.
$pdo = new PDO($dsn, $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET #myvar = 'myvalue', #myothervar = 'othervalue'"
]);
It's also possible to set session variables at any time after connect, with a call to $pdo->exec().
$pdo->exec("SET #thirdvar = 1234");
You can read session variables in your SQL queries:
$stmt = $pdo->query("SELECT #myvar, #myothervar");
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
print_r($row);
}
You can also read session variables in triggers:
CREATE TRIGGER mytrig BEFORE INSERT ON mytable
FOR EACH ROW
SET NEW.somecolumn = #myvar;

Warning: mysql_num_rows() But only on webhost, not localhost

On localhost this works great. But when I upload files to server I get this error:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /storage/content/04/13fd39104/xxxxx.com/public_html/users/list.php on line 54
My code is:
//load users from database
$users = mysql_query("SELECT id,username FROM ".$sql_table_users." WHERE id!='".$_SESSION['user_id']."'");
if(mysql_num_rows($users) > 0){
while($user = mysql_fetch_assoc($users)){
//ALT tag contains user ID and user name
print '• '.$user['username'].'<br />';
}
}
Are you sure to have the same db strutture on server? Probably some column or table name are different from localhost. Check also if your db connection credentials are correct
Perhaps your database on server is not the same as your localhost.
add echo mysql_error(); after mysql_query to see details.
I would echo the query string before performing the query to see if it really is the string you think it should be. Most likely one of the variables is not defined so the query is failing. If that doesn't help you could also output any mysql errors after the query.
And of course, the obligatory suggestion to get off of the deprecated mysql_* functions! If you don't want to do PDO, check out mysqli and how very similar it is to the mysql functions if you use the procedural functions.

Efficient way to connect to a database when multiple functions are running queries

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;.

MySQL resource in Zend Framework

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();

MySQL connection reuse problem

I am trying to reuse mysql connection. Hence I have a global variable in databasemanager.php class that returns a connection.
The problem is somehow on one particular page mysql is executing prior query as well.
Looks like there is some leftover query in connection object that gets executed if same connection is being reused . Is it possible ? how to solve this ..
function getDBConnection(){
global $conn;
if (!empty($conn)){
// echo $conn ;
return $conn;
}
$conn = mysql_connect($GLOBALS['HOSTNAME'],$GLOBALS['DBUSER'],$GLOBALS['DBPASS']);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($GLOBALS['DBNAME'],$conn);
return $conn;
}
This how code lookslike
Have you looked into mysql_pconnect?
According to the documentation:
mysql_pconnect() acts very much like
mysql_connect() with two major
differences.
First, when connecting, the function
would first try to find a (persistent)
link that's already open with the same
host, username and password. If one is
found, an identifier for it will be
returned instead of opening a new
connection.
Second, the connection to the SQL
server will not be closed when the
execution of the script ends. Instead,
the link will remain open for future
use (mysql_close() will not close
links established by
mysql_pconnect()).