In certain functions I may need to do a couple of queries like so:
$user = & JFactory::getUser();
$db = & JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id');
$query->from($db->quoteName('#__users'));
$query->where('username='.$db->quote($response->username));
$db->setQuery($query);
$user_id = $db->loadResult();
if ($user_id == "")
{
//do something
}
$query1 = $db->getQuery(true);
$query1->select('app_id');
$query1->from($db->quoteName('#__app_ids'));
$query1->where('app_descr='.$db->quote($this->app_descr).' AND app_valid=TRUE');
$db->setQuery($query1);
$app_id = $db->loadResult();
I find if I don't change query to query1 I can't get this to work for the subsequent queries. Outside of Joomla I've never had to do this as I close the mysql connection use the same variable as long as it is in the right order, all is well.
Two questions:
Is this right? Or is there a better way to do this?
Do I need to check for mysql failure of loadResult? How would I go about this. Looking at the Joomla core often I see nothing but sometimes there is a mix of things to handle this.
1) It should work with the same variable name, since you are getting a new query object since your method parameter is set to true. Try calling $query->clear(); just after getting query object
$query = $db->getQuery(true);
$query->clear();
$query->select('app_id');
2) In Joomla 3 it should be something like
try
{
$db->setQuery($query);
$user_id = $db->loadResult();
}
catch (RuntimeException $e)
{
$e->getMessage();
}
And in Joomla 2.5
if ($db->getErrorNum()) {
JError::raiseWarning(500, $db->getErrorMsg());
}
Also, change
$user = & JFactory::getUser();
$db = & JFactory::getDBO();
to
$user = JFactory::getUser();
$db = JFactory::getDBO();
Objects are returned by reference anyway in PHP 5, and it will throw a warning since php 5.3+
Well, on Joomla the JFactory::getDBO() always returns the same instance of connection,(at the atual version today) so each time you set the SQL you, in true, are rewriting the previous SQL. In resume this code need multiple connections, and this way dont support, you will need to write your own version of JDatabaseDriver, maybe your own version of a global static array to control your own pool of mysqli connections. PHP is poor about pool connections, isn't as JAVA or .NET, to quick code you will need to think the logic and to try to use only one connection each time, one opened query each time, always think that the JFactory::getDBO() isn't thread safe, take care about this. You never can start one transaction inside one php without commit ou rollback, it causes problems on execution of other pages.
Related
When reading on php.net about MySQL functions. I encountered this message
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
I've read about PDO. How can I update my code to PDO using either MySQL or MSSQL?
I see a lot of code posted on SO implementing my_sql functions. And comments from others (including myself) pressing the questioners to abandon MySQL functions and start using PDO or MySQLI. This post is here to help. You can refer to it as it provides explanation to why they are deprecated and what PDO is, plus a minimal code example to implement PDO.
First of all:
Conversion from mysql functions to PDO is not a simple case of search and replace. PDO is an Object Oriented Programming add on for the PHP language.
That means an other approach in writing the code as with the mysql functions. First why convert?
Why are mysql functions deprecated?
The mysql extension is ancient and has been around since PHP 2.0, released 15 years ago (!!); which is a decidedly different beast than the modern PHP which tries to shed the bad practices of its past. The mysql extension is a very raw, low-level connector to MySQL which lacks many convenience features and is thereby hard to apply correctly in a secure fashion; it's therefore bad for noobs. Many developers do not understand SQL injection and the mysql API is fragile enough to make it hard to prevent it, even if you're aware of it. It is full of global state (implicit connection passing for instance), which makes it easy to write code that is hard to maintain. Since it's old, it may be unreasonably hard to maintain at the PHP core level.
The mysqli extension is a lot newer and fixes all the above problems. PDO is also rather new and fixes all those problems too, plus more.
Due to these reasons* the mysql extension will be removed sometime in the future.
source Deceze
How to implement PDO
PDO offers one solution for connecting to multiple databases. This answer covers only MySQL and MSSQL servers.
Connecting to a MySQL database, prerequisites
This is fairly simple and doesn't require any pre set-up of PHP. Modern PHP installations are standard shipped with a module that allows PDO connections to MySQL servers.
The module is php_pdo_mysql.dll
Connecting to a MSSQL database, prerequisites
This is a more advanced set-up. You need php_pdo_sqlsrv_##_ts.dll or php_pdo_sqlsrv_##_nts.dll drivers. They are version specific hence the ##. At the moment of writing, Microsoft has released
official drivers for PHP 5.5.x. The 5.6 drivers aren't yet officially released by Microsoft, but are available as non-official builds by others.
The module is php_pdo_sqlsrv_##_ts.dll for the thread safe variant
The module is php_pdo_sqlsrv_##_nts.dll for the non-thread safe variant
Connecting to a database using PDO
To connect to a database you need to create a new PDO instance from the PDO construct.
$connection = new PDO(arguments);
The PDO constructor takes 1 required arguments and 3 optional.
DSN or Data Source Name, mostly this is a string containing information about the driver, host and database name. Since PHP 7.4 it can also include username and password.
Username
Password
Options
Connecting to MySQL
$dsn = 'mysql:dbname=databasename;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
Let's take a look at $dsn: First it defines the driver (mysql). Then the database name and finally the host.
Connecting to MSSQL
$dsn = 'sqlsrv:Server=127.0.0.1;Database=databasename';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
Let's take a look at $dsn: First it defines the driver (sqlsrv). Then the host and finally the database name.
When you create the instance a connection is made to the database. You only have to do this once during the execution of a PHP script.
You need to wrap the PDO instance creation in a try-catch clause. If the creation fails a back trace is shown revealing critical information about your application, like username and password. To avoid this catch the errors.
try
{
$connection = new PDO($dsn, $user, $password);
}
catch( PDOException $Exception )
{
echo "Unable to connect to database.";
exit;
}
To throw errors returned by your SQL server add this options to your PDO instance using setAttribute: $connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
Performing queries
PDO uses prepared statements. This is a real difference between PDO's approach and mysql functions. The latter was very susceptible to SQL-INJECTION. One would build a query like this:
$SQL = 'SELECT ID FROM users WHERE user = '.$username ;
When a malicious website or person posts the username injector; DROP TABLE users. The results will be devastating. You needed to proof your code by escaping and encapsulating strings and variables with quotes. This had to be done
for every query. On larger websites or poorly maintained code the risk of having a form that allowed SQL injection could become very high. Prepared statements eliminates the chance of first tier SQL injection like the example above.
The PDO drivers act as a man-in-the-middle between your PHP-server and database server, called a data-access abstraction layer. It doesn't rewrite your SQL queries, but do offer a generic way to connect to multiple database types
and handles the insertion of variables into the query for you. Mysql functions constructed the query on execution of the PHP code. With PDO the query actually gets build on the database server.
A prepared SQL example:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
Note the difference; Instead of a PHP variable using $ outside the string, we introduce a variable using : within the string. Another way is:
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = ?';
How to perform the actual query
Your PDO instance provides two methods of executing a query. When you have no variables you can use query(), with variables use prepare(). query() is immediately executed upon calling. Please note the object oriented way of the call (->).
$result = $connection->query($SQL);
The prepare method
The prepare method takes two arguments. The first is the SQL string and the second are options in the form of an Array. A basic example
$connection->prepare($SQL, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
In our SQL string example we've used a named variable called :username. We still need to bind a PHP variable, integer or string to it. We can do this in two ways. Either build an array containing the named variables as key or use the method bindParam or bindValue.
I will explain the array variant and the method bindValue for the sake of simplicity.
Array
You can do something like this for named variables, where you provide the variable as array key:
$queryArguments = array(':username' => $username);
And this for indexed variables (?):
$queryArguments = array($username);
When you have added all the variables you need you can call upon the method execute() to perform the query. Thereby passing the array as argument to the function execute.
$result = $connection->execute($queryArguments);
bindValue
The bindValue method allows you to bind values to the PDO instance. The method takes two required arguments and one optional. The optional arguments set the data-type of the value.
For named variables:
$connection->bindValue(':username', $username);
For indexed variables:
$connection->bindValue(1, $username);
After binding the values to the instance, you can call upon execute without passing any arguments.
$result = $connection->execute();
NOTE: You can only use a named variable once! Using them twice will result in a failure to execute the query. Depending on your settings this will or will not throw an error.
Fetching the results
Again I will only cover the basics for fetching results from the returned set. PDO is a fairly advanced add-on.
Using fetch and fetchAll
If you did a select query or executed a stored procedure that returned a result set:
fetch
fetch is a method that could take up to three optional arguments. It fetches a single row from the result set. By default it returns an array containing the column names as keys and indexed results.
Our example query could return something like
ID EMAIL
1 someone#example.com
fetch will return this as:
Array
(
[ID] => 1
[0] => 1
[EMAIL] => someone#example.com
[1] => someone#example.com
)
To echo all output of a result set:
while($row = $result->fetch())
{
echo $row['ID'];
echo $row['EMAIL'];
}
There are other options you can find here: fetch_style;
fetchAll
Fetches all rows in a single array. Using the same default option as fetch.
$rows = $result->fetchAll();
If you used a query that didn't return results like a insert or update query you can use the method rowCount to retrieve the amount of rows affected.
A simple class:
class pdoConnection {
public $isConnected;
protected $connection;
public function __construct($dsn, $username, $password, $options = array()) {
$this->isConnected = true;
try {
$this->connection = new PDO($dsn, $username, $password, $options);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //sets the default to return 'named' properties in array.
} catch (PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function disconnect() {
$this->connection = null;
$this->isConnected = false;
}
public function query($SQL) {
try {
$result = $this->connection->query($SQL);
return $result;
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
public function prepare($SQL, $params = array()) {
try {
$result = $this->connection->prepare($SQL);
$result->execute($params);
return $result;
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
}
How to use:
$dsn = 'mysql:dbname=databasename;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$db = new pdoConnection($dsn, $user, $password);
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
$result = $db->prepare($SQL, array(":username" => 'someone'));
while($row = $result->fetch())
{
echo $row['ID'];
echo $row['EMAIL'];
}
is it safely way to use Mysqli_connect link in a function as GLOBALS like on following example ? What problems might I face on with this way ?
function dbconnect(){
$link = mysqli_connect($db['host'], $db['user'], $db['pass']);
mysqli_select_db($link, $db['db']);
return $link;
}
function something_query($sql){
return mysqli_query($GLOBALS['conn'], $sql);
}
$conn = dbconnect();
$newsql = 'select * from table where 1';
something_query($newsql);
edit 1 : $conn is an unique string on whole code and it does not use as param in query
Yes, it's save (as in, there are no security risks with it).
It is not the best design though. Dependency injection is generally preferred to global variables, as it gives you the opportunity of testing only a small part of your code, and mocking the rest that is not needed for that test, and it increases the reusability of your code (you can just take a class/function and use it in a different project, without reading all the code and checking what values need to exist in global).
I have installed the latest version of CI 2.1.3
Now after running a query, I am getting a very slow response time for something very simple such as:
function Bash(){
$sql = “SELECT * FROM Contacts”;
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
after querying a remote database. (Sql server 2008)
When I run this same query in a simple PHP script against the same remote database. I get results instantly.
a) Has anyone else experienced this problem with the sqlsrv drivers in codeigniter?
If so, how did you solve it?
Here is my connection string:
$db['default']['hostname'] = "xxxxx,1433";
$db['default']['username'] = "xx";
$db['default']['password'] = "xxxxxx-xx";
$db['default']['database'] = "xxxxxxxxx";
$db['default']['dbdriver'] = "sqlsrv";
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = TRUE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
UPDATE:
I have found the following from running the profiler.
DATABASE: database QUERIES: 1 (Hide)
0.0659 select * from Contacts
Loading Time: Base Classes 0.0428
Controller Execution Time ( Welcome / AzureBash ) 58.2173
Total Execution Time 58.2602
It seems as though the query is executing in 0.06 secs but the controller is taking a minute to load.
No idea why this is happening.
Solution
The active records interface for the latest SQLSRV drivers are buggy.
So, download and overwrite the existing interface with these (overwrite your sqlsrv folder in the database folder in CI):
http://www.kaweb.co.uk/blog/mssql-server-2005-and-codeigniter/
Note: These have been tested with SQL Azure and works.
$query->num_rows(); does not work with these drivers, so I suggest you use count instead. Or create your own wrapper.
In addition date is now a date object type in your result set.
I hope this helps.
Solution 2
If for whatever reason you find a bug that makes this completely unusable. Revert back to the sqlsrv interface originally provided. You will find what is causing the problem is the way the original interface are executing the query, thus, create a database helper class; use $sql = $this->db->last_query(); to get the query you was about to execute and then within the database_helper class execute it yourself:
function MakeDbCall ($sql)
{
$serverName = "xxxxx-xxxx-xxx,1433"; //serverName\instanceName
$connectionInfo = array( "Database"=>"xxx", "UID"=>"xx", "PWD"=>"xxxxx","ConnectionPooling" => "1");
$conn = sqlsrv_connect($serverName,$connectionInfo);
$stmt = sqlsrv_query($conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$result_array[] = $row;
}
return $result_array;
}
Create one for row_array.
You should be able to call this function directly, from anywhere in your app. Whilst taking advantage of the way active_records constructs your query.
Not an ideal solution, but until codeigniter sort their SQLSRV class, there is not a lot we can do.
Adding an answer to this after the answer has already been accepted because I found a different solution. I was having the same problem ... looping through the result set was very very slow. i opened system/database/drivers/sqlsrv/sqlsrv_driver.php and found the connection function. i noticed that is was using the SQLSRV_CURSOR_STATIC option. i changed this to SQLSRV_CURSOR_CLIENT_BUFFERED and my slowness problems went away. See documentation for this here:
http://msdn.microsoft.com/en-us/library/hh487160(v=sql.105).aspx
I honestly have no idea what the sql server driver for php is doing, however, given the speed up, etc i can guess that the driver might be using a cursor by default. this seems like an awful idea. i also am assuming that by choosing client_buffered the data for the query would b e read without a cursor and accessed in memory on the client as if it were a cursor. If this is the case, bad things might happen if you try to execute a query that has many many rows to read. Perhaps another option (SQLSRV_CURSOR_FORWARD?) can be used to read data without a cursor - but i'm sure the methods used to access the query will be more limited (e.g. not using result_array())
-Don
Solution
The active records interface for the latest SQLSRV drivers are buggy.
So, download and overwrite the existing interface with these (overwrite your sqlsrv folder in the database folder in CI):
http://www.kaweb.co.uk/blog/mssql-server-2005-and-codeigniter/
Note: These have been tested with SQL Azure and works.
$query->num_rows(); does not work with these drivers, so I suggest you use count instead. Or create your own wrapper.
In addition date is now a date object type in your result set.
Solution 2
If for whatever reason you find a bug that makes this completely unusable. Revert back to the sqlsrv interface originally provided. You will find what is causing the problem is the way the original interface are executing the query, thus, create a database helper class; use $sql = $this->db->last_query(); to get the query you was about to execute and then within the database_helper class execute it yourself:
function MakeDbCall ($sql)
{
$serverName = "xxxxx-xxxx-xxx,1433"; //serverName\instanceName
$connectionInfo = array( "Database"=>"xxx", "UID"=>"xx", "PWD"=>"xxxxx","ConnectionPooling" => "1");
$conn = sqlsrv_connect($serverName,$connectionInfo);
$stmt = sqlsrv_query($conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$result_array[] = $row;
}
return $result_array;
}
Create one for row_array.
You should be able to call this function directly, from anywhere in your app. Whilst taking advantage of the way active_records constructs your query.
Not an ideal solution, but until codeigniter sort their SQLSRV class, there is not a lot we can do.
What is your connection string? You can specify the "network protocol" explicitly, which somtimes can affect speed.
http://www.connectionstrings.com/articles/show/define-sql-server-network-protocol
"Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=pubs;User ID=myUsername;Password=myPassword;"
By specifying the IP address, the port number (1433) and the Network Library, you are providing a very granular connection string.
Your details may vary of course.
Alot of times, you don't need this. But I've been on a few client trips where this was the magic dust.
You might want to turn db_debug to FALSE which should save time debugging the database.
Also, would suggest to turn cache_on to FALSE and specify cachedir and use $this->db->cache_on(); for queries that are less dynamic, i.e. does not change frequently.
For speed up fetch up to 3 times please use "MultipleActiveResultSets"=>'0' in your sqlsrv_connect connection options.
Ex:
$db = sqlsrv_connect('127.0.0.1', array('Database'=>'dbname','UID'=> 'sa','PWD'=> 'pass',"CharacterSet" =>"UTF-8","ConnectionPooling" => "1"
,"MultipleActiveResultSets"=>'0'
));
I'm kinda going crazy about this problem. I can't do it myself so I need the community to help me get this thing solved. I've been spending hours on this because I didn't know where to look. I now know a possible fix but it's just messy (read on). I just need someone who knows more about this than I do.
This is my situation:
I want to use 2 or more mysql connections.
I use OOP
I have a class called dbase, it has two functions, setConnection and getConnection and two class variables called $connection and $dbaseName.
In my main project file I include dbase and create two objects:
dbase
maindbase
then I do:
$this->dbase->setConnection($server, $uname, $pword);
$this->maindbase->setConnection($server, $uname, $pword);
the setConnection function looks like this:
function setConnection ($server, $serv_Username, $serv_Password) {
$this->connection = mysql_connect($server, $serv_Username, $serv_Password, true);
// echo $this->connection . "<BR>";
}
I echo it to see the resourcenumber and added true to mysql_connect (and I know it's deprecated since 5.5, I'm not here for that).
Now, as I understand OOP, the class variables are set per object. So $connection from dbase will never be the same as maindbase (unless, of course, I use the same credentials, but even then it will create a new link because of the $new_link option I enabled). They both have different resource ID's.
My problem:
In class dbase I also have a function which runs a query like this:
$connection = $this->getConnection();
$dbase_name = $this->getDbaseName();
mysql_select_db($dbase_name, $connection);
$q = "SELECT * FROM {$table_name} WHERE {$column} LIKE '{$value}'";
$result = mysql_query($q);
Now, when I use it like this, it will ALWAYS use the FIRST $connection that has been set in class dbase and it doesn't matter which object this is, either object dbase or maindbase.
I get this error:
Table 'testdbase1.skye_domains' doesn't exist
object dbase is connected to testdbase1
object maindbase is connected to testdbase2
the above error I get when trying to select results using the maindbase object.
When I remove the $connection string from mysql_select_db it works perfectly because it will try to open a new connection as if using mysql_connect.
Why is this? This is impossible right? How can objectmaindbase have the same $connection as object dbase? They are in NO WAY connected to eachother... Is PHP somehow using a global mysql_connect variable or buffer which I'm not aware about?
I would like to keep using connectionstrings as this is just handy now and then. Leaving the $connection string out seems messy.
Does anybody have any suggestions I can try to make PHP (or my head) sane again?
Try to put echo $this->connection EVERYWHERE you use it. Also, create an "id" member and fill it with a unique value upon constructing a dbase-object and echo it along the value of $this->connection. This way you can track where what happens to your connection.
And check if there's maybe some place outside of the class that assigns $foo->connection. If you're not using "private" on the members, you're bound to have such problems when you e.g. forget to remove a hack or an experiment from unrelated parts of your code.
How can I check if a db-connection is open in PHP?
How can I get a reference to this connection?
How can I determine if it is MySQL, Postgres or something else?
Ideally you would know the variable the connection is saved into. Without this it becomes a hassle to find it. It means you would have to loop through every variable and test each one, but doing this for any reason can be a pain because it wont find variables outside of the current scope. You can loop the current variables using:
foreach(get_defined_vars() as $x){
// Code
}
To check if a variable is a valid connection you can use the below code, it should return an integer:
if(mysql_thread_id($connection){
// Connection exists
}
Once you know its a connection you can use the following to return the type of connection, eg, mysql.
echo get_resource_type($connection);
You'd have to iterate over every defined variable and figure out if it's a resource handle or not. Try get_defined_vars().
Probably the best solution to the problem is to not lose track of the DB connection in the first place.
Consider integrating an ORM into your project such as Doctrine or Propel, or if you want something a little more lightweight, consider a DBAL such as Zend_Db. All of these solutions encapsulate the database connections in class instances, ensuring that they are always available to your code if necessary.
In general terms, I don't think it's really possible, not at least with some sort of complicate workaround. You can, for instance, loop through all defined variables:
foreach(get_defined_vars() as $variable){
if( is_resource($variable) && get_resource_type($variable)=='mysql link' ){
// Found a connection!
var_dump($variable);
}
}
Though, in fact, a connection remains available even if assigned to a local variable out of current scope:
function foo(){
$conn = mysql_connect('localhost', 'test', 'test');
}
foo();
$res = mysql_query('SELECT NOW() AS what_is_the_time');
if( $row = mysql_fetch_assoc($res) ){
var_dump($row);
}
The problem is that PHP doesn't really care about variables when talking about connections:
// One connection and zero variables!
mysql_connect('localhost', 'test', 'test');
$res = mysql_query('SELECT NOW() AS what_is_the_time');
if( $row = mysql_fetch_assoc($res) ){
var_dump($row);
}
You can try and find information about current connection:
var_dump(mysql_thread_id());
// int(2696)
... though many of the functions will just attempt to stablish a new connection if there isn't one so must take care of warnings...:
Warning: mysql_thread_id(): Access denied for user ''#'localhost' (using password: NO)
bool(false)
... unless your configuration actually allows a succesful credential-less connnection attempt.
I'm pretty sure that, whatever you want to do, can be done in an entirely different way :)