I have just changed the connection driver (extension) from mssql_connect to work with sqlsrv_connect. Unfortunately things do not seem to work as I wanted. I'd appreciate if someone can tell me what’s wrong and how can I fix it.
Code excerpt:
//a oracle DB moudle with a generic functions such as
//db_connect() db_query()
/// turn on verbose error reporting (15) to see all warnings and errors
error_reporting(15);
//generic DB operations
// Global record . for using in
$curr_rec = NULL;
function dbok($res)
{
if($res==false){
echo "DB error: "."FIXME need error mesg"."\n";
exit;
}
return $res;
}
function db_now_expr()
{
return "getdate()";
}
function db_is_connected($dbh)
{
return $dbh>0;
}
function ensure_connected($dbh)
{
if(!db_is_connected($dbh)) die("DB is not connected, operation failed");
//echo "DEBUG: hdb=$dbh";
}
//connect to given database
//return handler to DB
function dbo_logon($dbserver,$dbname)
{
$tsql = ??????? ====>>> what should i put here????
$dbserver = "computername\SQLEXPRESS";
$dbname = MY_Database_name;
$connectionOptions = array("Database"=>"BULL");
$dbh=dbok(sqlsrv_connect($dbserver, $connectionOptions));
dbok(sqlsrv_query($dbname,$dbh));
$stmt = sqlsrv_query( $connectionOptions, $tsql );
return $dbh;
}
//close DB
function dbo_logoff($dbh)
{
if(!db_is_connected($dbh)) echo("DB disconnect error");
sqlsrv_close($dbh);
}
Here is the original code using mssql_connect:
//a oracle DB module with a generic function such as
//db_connect() db_query()
/// turn on verbose error reporting (15) to see all warnings and errors
error_reporting(15);
//generic DB operations
// Global record . for using in
$curr_rec = NULL;
function dbok($res)
{
if($res==false){
echo "DB error: "."FIXME need error mesg"."\n";
exit;
}
return $res;
}
function db_now_expr()
{
return "getdate()";
}
function db_is_connected($dbh)
{
return $dbh>0;
}
function ensure_connected($dbh)
{
if(!db_is_connected($dbh)) die("DB is not connected, operation failed");
//echo "DEBUG: hdb=$dbh";
}
//connect to given database
//return handler to DB
function dbo_logon($dbserver,$dbuser,$dbpass,$dbname)
{
// $dbh=dbok(mssql_pconnect($dbserver,$dbuser,$dbpass));
$dbh=dbok(mssql_connect($dbserver,$dbuser,$dbpass));
//error_log("connect to [$dbname]".date("His")." \r\n",3,"/tmpbull.log"); //DBEUG DELME
dbok(mssql_select_db($dbname,$dbh));
//dbo_exec($dbh,"alter session set NLS_DATE_FORMAT='dd-mm-yyyy //hh24:mi:ss'");
return $dbh;
}
//close DB
function dbo_logoff($dbh)
{
if(!db_is_connected($dbh)) echo("DB disconnect error");
mssql_close($dbh);
}
Note that I had to change the authentication method from SQL authentication to Windows authentication because sqlsrv_connect uses Windows authentication instead of SQL authentication. Is that right?
I think these two links will help to understand Difference between mssql and sqlsrv
http://blogs.msdn.com/b/brian_swan/archive/2010/03/08/mssql-vs-sqlsrv-what-s-the-difference-part-1.aspx
http://blogs.msdn.com/b/brian_swan/archive/2010/03/10/mssql-vs-sqlsrv-what-s-the-difference-part-2.aspx
Though in short, to quote one of the articles:
The sqlsrv driver is built, maintained, and supported by Microsoft`
and
The mssql driver is a community-built driver.
I’m not sure how recently this driver was updated or maintained as an official PHP extension, but as of the release of PHP 5.3, it is no longer available with PECL. A quick internet search turns up a few places to download the mssql driver, but none of them that I’ve found indicate that the driver is being actively maintained.
Source: http://blogs.msdn.com/b/brian_swan/archive/2010/03/08/mssql-vs-sqlsrv-what-s-the-difference-part-1.aspx
As for your code sample, see below:
$dbserver = "computername\SQLEXPRESS";
$dbname = "BULL";
$connetion = dbo_logon($dbserver,$dbname);
function dbo_logon($dbserver,$dbname) {
$connectionOptions = array("Database"=>$dbname);
$dbh=sqlsrv_connect($dbserver, $connectionOptions);
if(!$dbh){
die("Error in Database connection");
return false;
}
return $dbh;
}
I think this will work for the connection.please note the code is not tested.
"The sqlsrv driver is built, maintained, and supported by Microsoft`" well right now Sep 2014, there is no official release to support php 5.6 last official release is from april 2012. MS style...
Related
I have a project which has been developed in php 4 now it has to be upgraded to php 7.
The database is connected via odbc connection. When i try to connect to the database and run the index file nothing seems to pop up.
What i have done is i have converted my database into mysql and tried to connect to the database and it is connecting .
How do i change the complete odbc to mysql?
Please find below the odbc dataconnection file and let me know how to i connect it with mysqli.
<?php
//##################### ODBC CONNECT #######################
class DBConnectionManager{
var $DB;
function DBConnectionManager(){
$this->DB=$this->DBConnect();
}
function DBConnect()
{
//connection to database
// $dbconnect = odbc_connect(DB_SOURCE_NAME,DB_USERNAME,DB_PASSWORD)
$dbconnect = new mysqli("localhost",DB_USERNAME,DB_PASSWORD);
or die("Unable to Connect to SQL SERVER on ".DB_SOURCE_NAME);
return $dbconnect;
}
function DBexecute($query='')
{
$result = odbc_exec($this->DB,$query);
return $result;
}
function DBRows($query='')
{
$result=$this->DBexecute($query);
$num_row = 0;
while ($row = odbc_fetch_array($result))
{
$num_row++;
}
odbc_free_result($result);
return $num_row;
}
function mysqlFetchArray($arry){
return odbc_fetch_array($arry);
}
function closeConnection(){
if(isset($this->DB)){
odbc_close($this->DB);
unset($this->DB);
}
}
}
?>
What are the other changes i have to make?
Thanks in advance,
Renu
This question already has an answer here:
PHP: mysql_connect not returning FALSE
(1 answer)
Closed 8 years ago.
I'm very new to OOP and am trying to learn it. So please excuse my noobness. I'm trying to connect to mysql and to test whether the connection is successful or not, I'm using if-else conditions.
Surprisingly, the mysql_connect is always returning true even on passing wrong login credentials. Now I'm trying to figure out why it does and after spending about 20 minutes, I gave up. Hence, I came here to seek the help of the community. Here is my code:
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if(! $dbhandle)
{
die('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
$test = new test();
Please don't use the mysql_* functions, there are many, many reasons why - which are well documented online. They are also deprecated and due to be removed.
You'd be much better off using PDO!
Also I'd strongly advise abstracting this database code into a dedicated database class, which can be injected where necessary.
On-topic:
That code snippet seems to work for me, have you tried var_dumping $conn? Does that user have correct rights?
I also hope that you don't have a production server which allows root login without a password!
Ignoring the fact that you're using mysql_* functions rather than mysqli or pdo functions, you should utilise exceptions in OOP code rather than die(). Other than that, I can't replicate your problem - it may be that your mysql server is set up to accept passwordless logins.
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
// returns false on failure
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
throw new RuntimeException('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if (!$dbhandle)
{
throw new RuntimeException('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
try {
$test = new test();
} catch (RuntimeException $ex) {
die($ex->getMessage());
}
I'd like to backup my read replica(i.e., slave) database with my master database but this simple boolean I did failed:
$config['hostname'] = "myReadReplicaDatabase.com";
//...$config['other_stuff']; other config stuff...
$db_obj=$CI->load->database($config, TRUE);
if(!$db_obj){
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
After terminating my read replica database I expected the boolean to evaluate to FALSE and the script to then use my master database. Unfortunately, instead I got the following PHP error:
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
All i want is for the connection to return true or false, does anyone know how to do this in Codeigniter?
My question was answered on this thread on Codeigniter forums.
The key is to not autoinitialize the database:
$db['xxx']['autoinit'] = FALSE;
To suppress errors it you can set this
$db['xxx']['db_debug'] = FALSE;
Then in your code that checks the db state, check TRUE/FALSE of the initialize() function:
$db_obj = $this->database->load('xxx',TRUE);
$connected = $db_obj->initialize();
if (!$connected) {
$db_obj = $this->database->load('yyy',TRUE);
}
Here is my entire config file for future reference: https://gist.github.com/3749863.
when you connect to database its returns connection object with connection id on successful condition otherwise return false.
you can check it to make sure that database connection is done or not.
$db_obj=$CI->load->database($config, TRUE);
if($db_obj->conn_id) {
//do something
} else {
echo 'Unable to connect with database with given db details.';
}
try this and let me know, if you have any other issue.
I test all I found and nothing wokrs, the only way I found was with dbutil checking if database exists, something like this:
$this->load->database();
$this->load->dbutil();
// check connection details
if( !$this->dbutil->database_exists('myDatabase'))
echo 'Not connected to a database, or database not exists';
Based on what was said here:
Codeigniter switch to secondary database if primary is down
You can check for the conn_id on the $db_obj
if ($db_obj->conn_id === false) {
$config['db_debug'] = true;
$config['hostname'] = "myMasterDatabase.com";
$db_obj=$CI->load->database($config, TRUE);
}
This should work.
try {
// do database connection
} catch (Exception $e) {
// DO whatever you want with the $e data, it has a default __toString() so just echo $e if you want errors or default it to connect another db, etc.
echo $e->getMessage();
// Connect to secondary DB.
}
For those who downvoted me, you can do this. Exception will catch PDOException.
try {
$pdo = new PDO($dsn, $username, $password);
} catch(PDOException $e) {
mail('webmaster#example.com', 'Database error message', $e->getMessage());
// and finally... attempt your second DB connection.
exit;
}
$readReplica = #$CI->load->database($config, TRUE); // ommit the error
if ($readReplica->call_function('error') !== 0) {
// Failed to connect
}
Im not sure about the error code (not sure if its int/string) and don't have CI nearby to test this out but this principle should work
$this->load->database();
print_r($this->db);
Its work for me
$config['xxx'] = xx;
...
$config['db_debug'] = false;
$db_obj = #$this->load->database($config,true);
if(!#$db_obj->initialize()){
echo "Unable to connect database";
die;
}
I want to call multiple MySQL stored routines sequentially with PHP, but I can only call a single one successfully---after that I get the error Commands out of sync; you can't run this command now. Researching the problem I found it's a common headache (caused by not "finishing up" the previous call before the next one is made), but I didn't find a solution I could apply to my code:
for ($i=0; $i<10; $i+=1)
{
if (!($conn=getconn() && ($result=mysql_query("call MyStoredRoutine();", $conn))))
{
$errorMessage = mysql_error($conn); // Error 2nd time here...
}
else {
while ($row=mysql_fetch_array($result)) {
// Retrieve data here...
}
}
}
And the implementation of getconn() (I don't think it's relevant but you never know):
function getconn() {
global $custdb, $custdb_connection, $dbuser, $dbpass;
if (! $custdb_connection) {
if (! ($custdb_connection = mysql_connect("localhost", $dbuser, $dbpass, true))) return false;
if (! (# mysql_select_db($custdb, $custdb_connection))) return false;
}
return $custdb_connection;
}
PHP version is 5.3.8-1~dotdeb.1, MySQL is 5.1.54-1ubuntu4.
Anybody knows what I should do to my code to make it work?
Maybe switch to MySQLi and use multi-query()
MySQLi gives you the added benefit of prepared statements and is build to support OOP.
I'm working on a web application written with PHP and uses SQL Server 2008. To connect to database, I used SQLSRV driever of Microsoft. In a part of this application, I have to use SQL Transactions. As Microsoft suggested, I did it exactly based on this article. The main processes in my codes follow these steps:
1- starting sql transaction
2- send information to PHP files through jQuery and check the result sent by JSON
3- rollback if the result was false and go to the next query if it was true.
4- commit transactions if no error occurred and all results were ok.
// This is my pseudo code
if (sqlsrv_begin_transaction( $sqlsrv->sqlsrvLink ) === true) {
$firstQuery = sqlsrv_query($stmt1);
if (!$firstQuery) {
sqlsrv_rollback();
} else {
$nextQuery = sqlsrv_query($stmt2);
if (!$nextQuery) {
sqlsrv_rollback();
} else {
sqlsrv_commit();
}
}
} else {
print_r(sqlsrv_errors()); // Here is where I get the error below.
}
The problem I have is this error:
[Microsoft][SQL Server Native Client 10.0][SQL Server] New transaction is not allowed because there are other threads running in the session
I'm using SQLSRV driver ver.2.
What is this error for? How can I solve it?
I included the my own sqlsrv class to the first part of index.php containing the methods below:
function __construct($dbServerName,$dbUsername,$dbPassword,$dbName)
{
$connectionInfo = array("Database"=> $dbName, "CharacterSet" => "UTF-8");
$this->sqlsrvLink = sqlsrv_connect($dbServerName, $connectionInfo);
if ($this->sqlsrvLink === false) {
$this->sqlsrvError = sqlsrv_errors();
}
}
function __destruct()
{
sqlsrv_close($this->sqlsrvLink);
}
i think you should set MultipleActiveResultSets to true when you want to connect to sql server :
$conn = sqlsrv_connect('127.0.0.1', array
(
'Database' => 'Adventureworks',
'MultipleActiveResultSets' => true, // MARS ENABLED
));
http://php.net/manual/de/ref.pdo-sqlsrv.connection.php
From your error, It seems like $nextQuery = sqlsrv_query($stmt2); is starting a new transaction in the same session. Can you commit !$firstQuery before starting the second?