PHP PDO DbLib - SQLSTATE[01002] Adaptive Server connection failed (severity 9) - php

in my PHP application I am suing PDO DbLib driver to connect to Microsoft SQL Server database and sometimes I am getting this PDO Exception:
SQLSTATE[01002] Adaptive Server connection failed (severity 9)
The weird thing is, that I am not getting this exception always, only sometimes. Sometimes I get that exception once per 10 executions, sometimes once per 50 executions of the application.
This is the database class constructor, which is initialising database connection:
function __construct($SQLHOST, $SQLPORT, $SQLDB, $SQLUSER, $SQLPWD, $SQLDRIVER)
{
try {
$pdo_connect = "dblib:version=8.0;host=" . $SQLHOST . ":" . $SQLPORT . ";dbname=" . $SQLDB . ";";
$this->db = new PDO($pdo_connect, $SQLUSER, $SQLPWD);
} catch (PDOException $e) {
$this->dead = true;
$this->error = "PDOException: " . $e->getMessage();
}
}
Any ideas what could be wrong?

Related

PHP MySQL PDO Connection to Google Cloud SQL Instance from VM Instance not working

DSN is:
mysql:dbname='MyDB';unix_socket='/cloudsql/ethereal-accord-123456789:us-central1:dev-Instance'
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
PDO Connection Code:
try {
$conn = new PDO($dsn, $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
return $conn;
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage().' <BR>';
}
I Cannot seem to find detail information on how to setup the connections correctly.
I follow all documents and activated the permissions for the VM IP, the Client SQL API, and Admin API, and nothing..
Any Help will be appreciated.
You don't run the cloudsql proxy or you have defined another location for the socket file. You should check this.
./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:3306 &
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=DATABASE_NAME';
https://cloud.google.com/sql/docs/mysql/connect-external-app#pdo-tcp
I reverted my code back to MYSqli instead of PDO using these lines
$host_name = "35.222.111.111";
$database = "myDB123";
$user_name = "dbuser123";
$password = "pass12345";
$GCSocket ="/cloudsql/ethereal-accord-2000000:us-central1:dev-instance-1"; $GCPort='3306';
$connect = mysqli_connect($host_name, $user_name,$password,$database,$GCPort,$GCSocket )
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error() ."<br>";
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL ."<br>";
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL ."<br><br>";
} else {
echo 'DB is connected..! <BR>';
}
return $connect;
The issue was not with the above code, it worked all along, the issue was with permission.
I whitelisted my IP from my Compute Engine VM in the Cloud SQL Server
give permission to your Compute Engine Service Account to access the Cloud SQL
Cloud SQL Client or Cloud SQL Admin
Execute this in the Compute Engine VM:
setsebool -P httpd_can_network_connect_db 1
and voila...
here is where i found the answer!

Is there a way for PHP PDO to detect if a t-sql database is being restored?

I'd like my PHP script (using PDO) to detect whether or not a target database is in the middle of a restore process other than waiting several minutes for a response from a failed connection.
My database connection code eventually returns the message below if a database is being restored, but it happens because the connection fails and it takes several minutes to respond when this happens. Searching on StackOverflow and Google doesn't seem to find anything that fits my need, nor does searching through PHP's documentation.
function getParameterizedPDOConnection($host = false, $overrideOptions = []) {
include(INCLUDE_DIR . "/itrain.config.php");
$host = strtolower($_SERVER["HTTP_HOST"]);
if (count($overrideOptions) > 0) {
$configOptions["host"][$host] = $overrideOptions;
}
$sthUserName = $configOptions["userName"];
$pwd = $configOptions["pwd"];
$addr = $configOptions["host"][$host]["addr"];
$db = $configOptions["host"][$host]["db"];
try {
$pdo = new PDO("sqlsrv:Server=$addr;Database=$db;ConnectionPooling=0", $sthUserName, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
return($pdo);
} catch (PDOException $e) {
return "Database connection failure: " . $e->getMessage();
}
}
Returns: "42000",927,"[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Database 'Workforce' cannot be opened. It is in the middle of a restore.

Connection between PHP and SQL server using WAMP new approaches

what is the best way for create a connection between PHP and SQL server that are seperate?(two server: server a SQL and server b PHP)
notice that I use wamp.
I read some articles like below but I want to know is there any new idea?
I test this code that works perfectly:
try{
$user = 'user';
$password = 'pass';
$server="localhost";//or server IP
$database="database";
$conn = odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", $user, $password);
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
I use PDO_ODBC Method:
1- Install ODBC on server that has wamp and enable PHP_PDO_ODBC extension on your wamp
2- Use this code that supports UTF-8:
try{
$hostname = "IP";
$dbname = "database";
$username = "username";
$pw = "password";
$pdo = new PDO ("odbc:Driver={SQL Server Native Client 10.0};Server=$hostname;Database=$dbname; Uid=$username;Pwd=$pw;");
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
$query = $pdo->prepare("select field_name from table");
$query->execute();
for($i=0; $row = $query->fetch(); $i++){
echo iconv("CP1256","UTF-8", $row['field_name'])."<br>";
}
3- replace these Items with yours:
IP-database-username-password-field_name-table
4- sometimes you need use "SQL SERVER" instead of "SQL Server Native Client 10.0" and sometimes you need use "IP,port" instead of "IP" and sometimes you need use "ISO-8859-6" instead of "CP1256".
From the PHP manual: http://php.net/manual/en/pdo.construct.php
Example #1 Create a PDO instance via driver invocation
<?php
/* Connect to a SQL Server database using driver invocation */
$dsn = "sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName#12345abcde", "Password";
try {
$dbh = new PDO($dsn);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Just change the HOST ip to the IP and port of your mysql server.

php connect to mysqlworkbench localhost

I have a mac with OSX 10.8.4. I have installed my localhost and it works just fine. I have made a php script, from where I would like to connect MySQL workbench database to. My apache tomcat server runs, and also mysql on the computer, and I use XAMPP. This is my code:
<?php
// Establish connection to DB using PDO
try {
$pdo = new PDO('127.0.0.1:3306', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
echo "Connected!";
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo "Connection failed";
exit();
}
I have tried this script to connect to a remote mysql server, where it works fine, but I cannot use it for my localhost. I also tried just to put in localhost in new PDO, but still the same. Does anybody have a clue to what is wrong?
Best Regards
Mads
You'll have an easier time knowing what's not working if you echo the exception being thrown.
Your code
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo "Connection failed";
}
doesn't actually print the exception! Try this instead:
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo $error;
}
That will at least give you some helpful debugging info.

I can not connect with PHP PDO

In my PHP apicación I connect to a MySQL database with PDO, but I'm having the following problem, the error message;
Warning: PDO :: __construct () [pdo. - Construct]: [2002]
"No connection Could be made ​​Actively Because the target machine refused it."
(trying to connect via tcp :/ / localhost: 3306)
Fatal error: Uncaught exception 'Exception' with message 'Connection failed: SQLSTATE [HY000] [2002]
The code to access the database is:
private $db = NULL;
const DB_SERVER = "localhost";
const DB_USER = "root";
const DB_PASSWORD = "usbw";
const DB_NAME = "status_poster";
public function __construct() {
//**below the error here!!**
$dsn = 'mysql:dbname=' . self::DB_NAME . ';host=' . self::DB_SERVER;//
//var_dump($dsn);
try {
$this->db = new PDO($dsn, self::DB_USER, self::DB_PASSWORD);
} catch (PDOException $e) {
throw new Exception('Connection failed: ' . $e->getMessage());
}
return $this->db;
}
What I find strange is that the same parameters to connect to "mysqli" I have no problems and I connect successfully, run CRUD statements and no problems, the code is as follows;
The code
function getProducts() {
$products = array();
$mysqli = new mysqli("localhost", "root", "usbw", "Datos");
if (mysqli_connect_errno()) {
printf("Error in conection: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Id,sku,name,price FROM products";
if ($result = $mysqli->query($query)) {
while ($obj = mysqli_fetch_object($result)) {
//instructions...
}
}
$mysqli->close();
return $products;
}
Well, I need to connect with PDO but I can not find the solution,
waiting for suggestions or help!
Sorry, can not find in the forum how to respond with a picture, but is this;
solve my problem, change the port from 3307-3306 (3306 was the port that went out in error) of USBWebserver. now work!
note: above the port was 3307
solve my problem, change the port from 3307-3306 (3306 was the port that went out in error) of USBWebserver. now work!

Categories