I am having trouble using my second database connection is codeigniter.
I have added the connection to database.php
$old = $this->load->database('old_portal', TRUE);
$sql = "SELECT * FROM `frm_root`";
$query = $this->old->query($sql);
But I am getting an error. I am not sure how to use the old object when wanting to use query()
Using multiple databases in CodeIgniter is pretty easy.
https://ellislab.com/codeIgniter/user-guide/database/connecting.html
You would do it like this;
$old = $this->load->database('old', true);
Then, you would access this database object, like this;
$query = $old->query();
Hope this helps.
$query = $old->query($sql);
Related
I'm building a CI application, and I need to use 2 different databases (mysql & mssql). When i try to run a simple query to the mssql DB then CI adds the dbprefix to the table names, so it ends up to an error. How is it possible to prevent CI adding the prefix? There is no dbprefix set in database.php file
Query in Model
public function getAccName($uid)
{
$this->load->database('mssqlsrv',TRUE);
return $this->db->where("uid", $uid)
->select("account")->get("user_account");
}
To answer this correctly:
When working with multiple database connections in Codeigniter each connection needs to be assigned to a variable like:
$DB1 = $this->load->database('mssqlsrv', TRUE);
$DB2 = $this->load->database('group_two', TRUE);
Then you can do the query with
$DB1->where("uid", $uid)->select("account")->get("user_account");
instead of
$this->db->where("uid", $uid)->select("account")->get("user_account");
See https://www.codeigniter.com/userguide3/database/connecting.html for more information on this.
How about trying to set each database connection to a certain variable:
like below code:
$mysqlConn = $this->load->database('mysql', TRUE);
$mssqlConn = $this->load->database('mssqlsrv', TRUE);
then try to use them for your query, for the code above it should be:
public function getAccName($uid)
{
$mssqlConn = $this->load->database('mssqlsrv', TRUE);
return $mssqlConn->where("uid", $uid)
->select("account")->get("user_account");
}
I have below query http://localhost/barbadosparliament/result/index?qry=testing
Now i want ot get data of qry parameter from url. But not able to get data. I used $this->uri->segment and also $_GET['qry']. But still i doesn't get that record. How can i get that record.
check you have on in config/config.php
$config['allow_get_array'] = TRUE;
then try
$qry = $this->input->get('qry', TRUE);
$qry = $_GET['qry'];
$qry = $_REQUEST['qry'];
Also try url like
http://localhost.com/barbadosparliament/result?qry=testing
try this:
$qry = $this->input->get('qry');
But this should works too
$qry = $_GET['qry'];
I have very little experience with joomla and sql and I would really appreciate your help!
I am using joomla 2.5 and I am querying data from the database and storing it in memory with the following code:
function getList()
{
$mainframe = JFactory::getApplication('site');
$db = JFactory::getDBO();
$query = " SELECT
*
FROM
#__ListUser
WHERE
$db->setQuery( $query );"
$rows = $db->loadObjectList();
return $rows;
}
I have 3 questions,
When I query the database, a new DB session is opened, Do I need to close it after or is automatic?
Do you know of a more efficient way to achieve this method (a user session memory size is about 11MB!)
Is there any security issue with accessing the database using this method?
Thank you very much! any help would be very appreciated!
The code should look like this (I don't see how it can work now):
function getList()
{
// $mainframe = JFactory::getApplication('site'); // you don't need this line!
$db = JFactory::getDBO();
$query = " SELECT
*
FROM
#__ListUser
WHERE
1=1"; // just some condition to extract selected rows
$db->setQuery( $query ); // this sets the query and it's joomla, not sql.
$rows = $db->loadObjectList();
return $rows;
}
Please note the WHERE .... needs a condition (else if you want all the rows, remove WHERE and what follows)
You don't need to close it
11Mb is not necessarily due to that query, try adding LIMIT 0,1 (to return just one row) you'll see your memory doesn't change much. Turn on debug in the global configuration, and reload the component. At the very bottom of the page you'll see which extensions are eating up your memory. 11Mb is acceptable though on most installations.
Should you create your WHERE condition using input params, just make sure you $db->quote() any values to prevent SQL-injection.
Try
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quote('*')
->from($db->quoteName('#__Listuser') // Do you really have upper case there?
->where('your condition with proper quoting');
$db->setQuery($query);
$rows = $db->loadObjectList();
1.
UNCOOL:
If you want to close or disconnect the database-session, you may use:
$db->disconnect(); // See: http://api.joomla.org/cms-3/classes/JDatabaseDriver.html#method_disconnect
But i guess, that the database-connection for every other module, plugin or template that want to use JFactory::getDBO(); is also closed then and needs to be reopened.
BETTER:
You should use FREE RESULT instead after a query is transfered to a PHP-Variable: http://api.joomla.org/cms-3/classes/JDatabaseDriverMysql.html#method_freeResult
$db->freeResult();
We have 2 different databases that I'm trying query against each other with an inner join.
When I run the query from phpmyadmin, the query works perfectly. However, when I attempt to put the query into a php page, I cannot get the line to work. I assume I'm missing something in the mysql_select_db line where I reference the host/db/user/pass for the first database.
What am I missing here to get this query to function on the page? Again, I'm confident the actual query works since it does run in phpmyadmin.
Thanks in advance as always.
Here's the code I'm working with....
$hostname_db = "123.456.78.910";
$database_db = "votes_db";
$username_db = "votes_dbuser";
$password_db = "password123";
$db = mysql_connect($hostname_db, $username_db, $password_db, true) or trigger_error(mysql_error(),E_USER_ERROR);
$hostname_db2 = "123.456.78.910";
$database_db2 = "survey_db";
$username_db2 = "survey_dbuser";
$password_db2 = "password456";
$db2 = mysql_connect($hostname_db2, $username_db2, $password_db2, true);
// trying to make this work, query ok in phpmyadmin, but not on the php page
mysql_select_db($database_db, $db);
$query_testdb3 = sprintf("SELECT votes_db.vote_table.vote_survey_id
FROM votes_db.vote_table
inner join survey_db.survey_table
ON votes_db.vote_table.vote_survey_id = survey_db.survey_table.survey_id
WHERE votes_db.vote_table.vote_survey_id = 1457 ");
$testdb3 = mysql_query($query_testdb3, $db) or die(mysql_error());
$row_testdb3 = mysql_fetch_assoc($testdb3);
$totalRows_testdb3 = mysql_num_rows($testdb3);
Sometime ago I have the same issue (mysql-php multiple databases problem)
So, remove the "true" option on the second ($db2) and everything should be fine.
Gl
$`totalRows_testdb3 = mysql_num_rows($testdb3);`
change the column # in "$testdb3" in the last line to "$row_testdb3".
$totalRows_testdb3 = mysql_num_rows($row_testdb3);
Also if you put each $db and db2 in separate class and function with a:
mysql_close($db);
after each query.
It was a permissions problem. The user that was connecting to the database didn't have the proper privliges. Hosting company fixed this for me, so I can't tell you exactly what they did, but it now works.
Tim was correct, it was working from phpmyadmin since I was logged in as a superuser...
I'm trying to create a more succinct way to make hundreds of db calls. Instead of writing the whole query out every time I wanted to output a single field, I tried to port the code into a class that did all the query work. This is the class I have so far:
class Listing {
/* Connect to the database */
private $mysql;
function __construct() {
$this->mysql = new mysqli(DB_LOC, DB_USER, DB_PASS, DB) or die('Could not connect');
}
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$info = $result->fetch_object() or die('Could not create object');
return $info;
}
}
This makes it easy to access any info I want from a single row.
$listing = new Listing;
echo $listing->getListingInfo('','Books')->title;
This outputs the title of the first listing in the category "Books". But if I want to output the price of that listing, I have to make another call to getListingInfo(). This makes another query on the db and again returns only the first row.
This is much more succinct than writing the entire query each time, but I feel like I may be calling the db too often. Is there a better way to output the data from my class and still be succinct in accessing it (maybe outputting all the rows to an array and returning the array)? If yes, How?
Do you actually have a performance issue?
If your current setup works and doesn't suffer from performance issues, I wouldn't touch it.
This sort of DB access abstraction will likely become a maintenance issue and probably won't help performance.
Also, you're susceptible to SQL injection.
You should be able to store the whole object from the query into a variable and then access the single values from that object:
$object = $listing->getListingInfo('','Books');
$title = $object->title;
$price= $object->price;
But you can also use fetch_assoc() and return the whole assiciative array:
$array = $listing->getListingInfo('','Books');
$title = $object['title'];
$price= $object['price'];
This will give you the same results and also with only one query to the DB.
EDIT: If the getListingInfo() is the only function you should think of the following:
rename the function to prepareListingInfo() and within the function only prepare the query and store it in a class variable.
add a getNextListingInfo() function, which will return an object or associative array with the next row.
Using this new function, you can get every row that matches your query.
Either cache the result in an internal var
Or Comment it with a warning and explain to function users to copy the result in an var instead of calling it again and again with the same params
Yes, that would be calling the db too often.
A couple of solutions
1) put the listing info in a variable
2) cache the results in a hashmap or dictionary (be careful for memory leaks)