Is there a way to connect a sqlserver using php-mssql DRIVER without a PDO connection on symfony?
I believe that you need to create your own driver for this purpose.
The abstract class Doctrine_Connection defines the way of connect.
On this class, in the method "connect" you can read:
if (extension_loaded('pdo')) {
find valid driver and load into PDO (calling PDO::getAvailableDrivers())
$found = true;
}
If driver is not found ( for example if you submit a dsn like this mssql_own:host=localhost;dbname=localdb ) then Doctrine_Connection makes:
$class = 'Doctrine_Adapter_' . ucwords("mssql_own");
if (class_exists($class)) {
$this->dbh = new $class($this->options['dsn'], $this->options['username'], $this->options['password'], $this->options);<br/><br/>
} else {
throw new Doctrine_Connection_Exception("Couldn't locate driver named " . "mssql_own");
}
You need to write this class named on my example "Doctrine_Adapter_Mssql_own" and make a connection with php-mssql.
I hope it helps...
Related
I've been struggling with this for quite a while, and it's to the point where I need to ask for help because even with all the research I've done I can't get a handle on why this is happening.
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1040] Too many connections'
This happens upon loading a single page (index.php), and I am the only user (dev). As you can see here, the MySQL connection limit is set # 50 but I am narrowly surpassing that. This is an improvement over the 100~ connections that were being created before I refactored the code.
Here are the stats after the page has loaded once.
I've narrowed the issue down to several causes:
I don't fully understand how PDO/MySQL connections work.
I am creating too many connections in my code even though I am trying to only create one that I can share.
I need to increase the connection limit (seems unlikely).
Most of the SO questions I've found, tell the OP to increase the connection limit without truly knowing if that's the best solution so I'm trying to avoid that here if it's not needed. 50 connections for one page load seems like way too many.
These are the classes I am instantiating on the page in question.
$DataAccess = new \App\Utility\DataAccess();
$DataCopyController = new App\Controllers\DataCopyController($DataAccess);
$DriveController = new App\Controllers\DriveController($DataAccess);
$Helper = new App\Utility\Helper();
$View = new App\Views\View();
I am creating the DAL object then injecting it into the classes that need it. By doing it this way I was hoping to only create one object and one connection, however this is not what's happening obviously. Inside the DAL class I've also added $this->DbConnect->close() to each and every query method.
Here is the constructor for the DataAccess() class.
public function __construct() {
$this->DbConnect = new \App\Services\DbConnect();
$this->db = $this->DbConnect->connect("read");
$this->dbmod = $this->DbConnect->connect("write");
$this->Helper = new Helper();
}
Here is the DbConnect() class.
class DbConnect {
private $db;
private $dbmod;
private function isConnected($connection) {
return ($connection) ? TRUE : FALSE;
}
public function connect($access) {
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
];
if ($access == "read") {
if ($this->isConnected($this->db)) {
return $this->db;
} else {
if (strpos($_SERVER['SERVER_NAME'], DBNAME_DEV) === false) {
$this->db = new PDO("mysql:host=127.0.0.1; dbname=".DBNAME,
DBUSER,
DBPASS,
$options
);
} else {
$this->db = new PDO("mysql:host=" . DBHOST_DEV ."; dbname=".DBNAME_DEV,
DBUSER,
DBPASS,
$options
);
}
return $this->db;
}
} elseif ($access == "write") {
if ($this->isConnected($this->dbmod)) {
return $this->dbmod;
} else {
if (strpos($_SERVER['SERVER_NAME'], DBNAME_DEV) === false) {
$this->dbmod = new PDO("mysql:host=127.0.0.1; dbname=".DBNAME,
DBUSER_MOD,
DBPASS,
$options
);
} else {
$this->dbmod = new PDO("mysql:host=" . DBHOST_DEV . "; dbname=".DBNAME_DEV,
DBUSER_MOD,
DBPASS,
$options
);
}
}
return $this->dbmod;
}
}
public function close() {
$this->db = null;
$this->dbmod = null;
}
}
I've also tried instantiating the DbConnect() class on index.php and injecting that rather than DataAccess() but the result was the same.
EDIT:
I also want to add that this MySQL server has two databases, prod and dev. I suppose the connection limit is shared between both. However, the prod database gets very little traffic and I am not seeing this error there. When I refreshed the stats, there were no connections to the prod database.
From the PHP manual ~ http://php.net/manual/en/pdo.connections.php
Many web applications will benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials.
So I would advise removing the DbConnection#close() method as you would not want to ever call this.
Also from the manual...
Note:
If you wish to use persistent connections, you must set PDO::ATTR_PERSISTENT in the array of driver options passed to the PDO constructor. If setting this attribute with PDO::setAttribute() after instantiation of the object, the driver will not use persistent connections.
So you'll want (at least)
new \PDO("mysql:host=127.0.0.1;dbname=" . DBNAME, DBUSER, DBPASS, [
PDO::ATTR_PERSISTENT => true
]);
You can also set your other connection attributes in the constructor.
hi friends ,
class MyDB extends SQLite3
{
function __construct()
{
$this->open('/var/cpanel/eximstats_db.sqlite3');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
i have using eximstats db from server. while on updating my server the eximstats db get got under the SQLite3. i am new one to SQLite3 even though I have tried many more times access that db using the above php code but never i got result . please help me to improve this coding.
Is this code is correct . while running this i got "Fatal error: Uncaught exception 'Exception' with message 'Unable to open database: unable to open database file' "
thank you
You can simply use PHP PDO interface to access your SQLite3 database.
$db = new PDO('sqlite:/var/cpanel/eximstats_db.sqlite3')
PDO_SQLITE DSN
To access a database on disk, append the absolute path to the DSN prefix.
Just make sure that you have the PDO Driver for SQLite 3.x installed on your system.
Now to select a table just do:
$result = $db->query('SELECT * FROM tablename');
foreach( $result as $row ) {
print_r( $row );
}
I'm trying to research how to integrate between magento and mongodb. At first, how to connect? and execute CRUD?
P/s: My system is using mysql, and I want to use mongodb too.
I based my work with mongo next to magento with this functionality github.com/colinmollenhour/magento-mongo
If you will have problems with connection change _newConnection metod in Mage_Core_Model_Resource to this:
protected function _newConnection($type, $config)
{
if ($config instanceof Mage_Core_Model_Config_Element) {
$config = $config->asArray();
}
if (!is_array($config)) {
return false;
}
$connection = false;
// try to get adapter and create connection
$className = $this->_getConnectionAdapterClassName($type);
if ($className) {
// define profiler settings
$config['profiler'] = isset($config['profiler']) && $config['profiler'] != 'false';
$connection = new $className($config);
if ($connection instanceof Varien_Db_Adapter_Interface) {
// run after initialization statements
if (!empty($config['initStatements'])) {
$connection->query($config['initStatements']);
}
} else {
$connection = false;
}
}
// try to get connection from type
if (!$connection) {
$typeInstance = $this->getConnectionTypeInstance($type);
$connection = $typeInstance->getConnection($config);
// if (!$connection instanceof Varien_Db_Adapter_Interface) {
// $connection = false;
// }
}
return $connection;
}
Regards,
Simply changing the connection layer won't work. You will need a full MongoDB abstraction layer to replace the MySQL abstraction layer plus underlying database.
Take a look at https://github.com/colinmollenhour/magento-mongo, which should get you started. I haven't used it myself so I cannot vouch for its quality or completeness.
PS: Why do you even want to replace MySQL? Unless you have very good reasons, I'd stay with the default as it be much better battle tested.
I'm sorry for the lack of information on this question I just need some advice on some code. I think only a programmer can answer this because my code is unique and I couldn't find any answers that help me.
Index.php
<?php
include ( 'Blue/BlueDatabase.php' );
include ( 'Blue/BlueUsers.php' );
use Blue\BlueDatabase;
use Blue\BlueLoader;
$database = new BlueDatabase();
$database->Connect('localhost', 'root', '', 'database');
?>
And now I have my "BlueLoader" class and I have this code in the class aswell
$database = new BlueDatabase();
$database->Connect('localhost', 'root', '', 'database');
What I want to know is. Is it worth adding that code to every class? It makes it look untidy and I think there will be a more stabler way of doing it. Do i need to do the connect function once ive done it before? does it need to be done for every class? I'm just new to php and unsure about some things. Is this script stable? / Secure
Any advice or answers will be helpful
Just incase you need my connect function (All my mysql commands are in an array like
//Example:
$commands['mysql_query'] = mysql_query;
final public function connect($sHost, $sUser, $sPass, $sName, $sPort = false, $sType = 'mysql_connect')
{
if(!$this->connected)
{
if ($sPort)
{
$sHost = $sHost . ':' . $sPort;
}
$this->connection = $this->_aCmd[$sType]($sHost, $sUser, $sPass);
if($this->connection)
{
$mydatabase = $this->_aCmd['mysql_select_db']($sName, $this->connection);
if($mydatabase)
{
$this->connected = true;
}
else
{
die('could not connect to database');
}
}
else
{
die('could not connect to host');
}
}
}
Advice:
Stop using the deprecated ext/mysql extension. Don't bother trying to wrap it in an OO framework.
Use PDO, because it already has a good OO usage, and has several other features that ext/mysql doesn't have. Mysqli is a runner-up, but I find PDO is easier to use.
Don't open a new connection in each class that uses a database. Create one connection and pass the connection object to each such class, probably as a constructor argument.
An alternative is to use a Registry class to store "global" objects like database connections.
Globals are great! They are perfect for indicating that you're taking a sub-optimal approach and you need to step back and re-evaluate.
Here are a few different ways you can address the issue.
$dbh = new DatabaseObject($connection_info);
$foo = new Object1($dbh);
$bar = new Object2();
$bar->GiveDbh($dbh);
$baz = new RegistryObject();
$baz->register('dbh', $dbh);
$bom = new Object3($baz);
I'd also include a Singleton method, but SO yells at me every time I do. :/
Also, you should probably re-jigger your database class to stop using mysql_* functions. Yadda yadda PDO MySQLi, you know the drill.
I have, what I think/hope, is a very simple PHP question. I have made a class to create database connections and issue common queries. I am trying to open two different database connections by creating two objects from the same database class. My code is as follows:
//connect to DB
$dbh = new DB('localhost', 'db1', 'user', 'pass');
//check connection
if(!$dbh->getStatus()) {
echo($dbh->getErrorMsg());
die;
}//if
//connect to DB 2
$dbh2 = new DB('localhost', 'db2', 'user', 'pass');
//check connection
if(!$dbh2->getStatus()) {
echo($dbh2->getErrorMsg());
die;
}//if
However, when I call a method for $dbh to query the database, it attempts to query with the credentials for $dbh2.
My DB constructor is below:
class DB {
function __construct($host, $db, $user, $pass) {
$dbh = mysql_connect($host, $user, $pass);
mysql_select_db($db, $dbh);
if(!$dbh) {
$this->status = false;
$this->error_msg = 'Error connecting to database: '.mysql_error();
return(false);
}//if
$this->dbh = $dbh;
$this->resetStatusAndErrors();
return($dbh);
}//_construct
Simple solution: Use PDO instead. It does exactly what you want, probably has better syntax and implementation and abstracts the interface for DB access.
You're not showing the full class, but the most probable reason is that you are not passing the current connection to the mysql_query() command.
Save $dbh as a property of your class, and add the connection parameter to each mysql_ function that accepts it:
mysql_query("SELECT * from.......", $this->dbh);
That said, if you are building this from scratch at the moment, take a look whether you don't want to use PDO instead. It is better, safer and more flexible than the old style mySQL library.
If you are using the mysql extension (using either mysqli or PDO_MySQL would give both superior performance, more features, etc., so check that for new code), you'll have to store the database handle, and use that on every mysql_* call:
class db {
....
function query($query){
return mysql_query($query, $this->dbh);//notice the second parameter.
}
}