Set appName for PDO connections made via PHP - php

I use PDO in PHP to connect to a PostgreSQL database.
Does it allow setting the application name when making this connection?
try {
$conn = new PDO ( 'pgsql:host=' . $host . ';dbname=' . $dbname, $user, $pwd );
//$conn->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
showError ( "Error", 2 );
}

You can add to the DSN string a new element called options with value --application_name=YOUR_NAME_HERE:
$conn = new PDO('pgsql:host=' . $host . ';dbname=' . $dbname . ';options=--application_name=YOUR_NAME_HERE', $user, $pwd );
Credit goes for this old user comment in PHP manual.

Related

Error during connect to mysql db via ssh: "Packets out of order. Got: 45 Expected: 0"

I'm trying to connect to a mysql via ssh in a php script.
I set a tunnel whit this command:
ssh -t myusername#ssh.studenti.math.unipd.it -L30080:tecweb:80 -L8443:tecweb:443 -L8022:tecweb:22
This is the php code:
$host = "localhost";
$port = "8022";
$dbname = "surbani";
$charset = 'utf8';
$user = "surbani";
$password = 'iequu2iJoo6eich7';
$dsn = 'mysql:host=' . $host . ';port=' . $port . ';dbname=' . $dbname . ';charset=' . $charset;
try {
$dbh = new PDO($dsn, $user, $password, array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
When I run it, it display the error: "Packets out of order. Got: 45 Expected: 0." and "MySQL server has gone away". I have no access to server, but when i connect to phpmyadmin through a broswer (localhost:30080/phpmyadmin) it works.
Could anyone help me please?
Thank for all in advance.
EDIT: I tried to add a new tunnel (-L33306:tecweb:3306) and change the port in php script. Same error in client, but the server console displays: "channel 9: open failed: connect failed: Connection refused"

PDO PgSQL sometimes doesn't connect

This is a awkward issue, and I'm running out of alternatives to workaround.
I have a server running Wamp 3.0.6, with PHP 5.6.
My code must connect in a MySQL (local) and a PostgreSQL (remote server).
Everything is working fine, and seemingly out of nowhere it stops returning data from PG. After few seconds or minutes, it just works again.
Even when I'm not able to get data from PG, phpPgAdmin keeps working.
Here is my connection function:
function pdo_pgsql($sql){
$host = '000.000.000.000';
$user = 'user';
$pass = 'pass';
$db = 'db';
try {
$PDO = new PDO( 'pgsql:host=' . $host . ';dbname=' . $db . ';port=5432', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
}
catch ( PDOException $e ) {
echo 'Error: ' . $e->getMessage(); exit;
}
$result = $PDO->query( $sql );
if (is_array($result)){
$row = $result->fetchAll( PDO::FETCH_ASSOC );
}else{
$row = $result;
}
return $row;
}
Any suggestion to help me with this?
Thanks
I have the same problem, and I found the solution, it is the PDO::ATTR_PERSISTENT need to be set to false.
This fixed my problem.

PHP - PDO SQLSRV - Connection string is not valid [87]

I´m trying to connect to a SQL Server 2008 R2 via PHP. I used the following code:
try {
$server = "servername.do.ma.in\\MSSQLSERVER";
$user = "username";
$pass = "password";
$db = "databasename";
$dbh= new PDO('sqlsrv:Server = ' . $server . '; Database = ' . $db, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Verbindung fehlgeschlagen: ' . $e->getMessage();
}
But when i run this code i get the following error:
SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87].
Does someone know this error and know what to do?
Thanks in advance.
Solution:
The Port was not defined. The following code worked for me.
I´ve added the Port 1433 to the $server Variable.
$server = "servername.do.ma.in, 1433";
$user = "username";
$pass = "password";
$db = "databasename";
$dbh = new PDO("sqlsrv:Server={$server};Database={$db};", $user, $pass);
This will work:
$dbh = new PDO("sqlsrv:Server={$server};Database={$db};", $user, $pass);
If it's still not valid, there's something wrong with your connection variables.
EDIT:
This looks similar to your problem:
http://laravel.io/forum/01-20-2015-sql-server-2012-db-connection-with-laravel-42

PDO error on __construct when host is not rigth [duplicate]

I'm trying to display a server status, based upon whether the database can be connected to or not. With the old school mysql_connect() and mysqli_connect() it was easy. I'm trying to stay modern, so I'm using PDO, but I can't figure out how-to suppress the default warning. From what I can tell, you need to use the getMessage() function for it to print the PDO warning, but I'm not using it.
Here's my code:
8 $dbstatus = 1;
9 try {
10 $db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd);
11 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
12 } catch(PDOException $e) {
13 $dbstatus = 0;
14 }
15 if($dbstatus == 1) {
16 echo '<span style="color: green">DB Up</span>';
17 } else {
18 echo '<span style="color: red">DB Down</span>';
19 exit;
20 }
All the connection variables are supplied and correct, except the $dbhost, which is intentionally broken to test this. Now, it produces the desired results, but is also prints a warning message too:
Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in C:\xampp\htdocs\cd\includes\dbconnect.php on line 10
If I correct the $dbhost variable, it works fine, so I know the issue isn't with the PDO statement being usable.
Any ideas on what I'm missing?
Solution
I used a variation of what was supplied by jeroen:
if(filter_var(gethostbyname($dbhost), FILTER_VALIDATE_IP)) {
$dbstatus = 1;
try {
$db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname, $dbuser, $dbpasswd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(PDOException $e) {
$dbstatus = 0;
}
} else {
$dbstatus = 0;
}
if($dbstatus == 1) {
echo '<span style="color: green">DB Up</span>';
} else {
echo '<span style="color: red">DB Down</span>';
exit;
}
Thank you for the help and I hope this helps someone else! ^^
The only thing I can see here, is that you tell PDO to throw exceptions after you have tried to open the connection. That is most likely too late.
What you could do instead, is send that option to the constructor directly using the 4th parameter:
try {
$opts = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$db = new PDO($dbms . ':host=' . $dbhost . ';port=' . $dbport . ';dbname=' . $dbname,
$dbuser, $dbpasswd, $opts);
} catch(PDOException $e) {
...
That will probably solve your problem.
Edit: If the host name is provided by the user, you could validate it before sending it to the PDO constructor.
For example using:
if (filter_var(gethostbyname($user_provided_host_name), FILTER_VALIDATE_IP)) {
// valid hostname / ip address
}
That will work for domain names, localhost and ip addresses.

Reusing variables when working with PDO

I have to pull data from at least 3 databases, is there anything wrong with reusing my PDO objects?
$dbh = new PDO('mysql:host=' . $host . ';dbname=' . $db_name, $user, $password);
$sth = $dbh->prepare($query1);
// do something
$dbh = new PDO('mysql:host=' . $host2 . ';dbname=' . $db_name2, $user2, $password2);
$sth = $dbh->prepare($query2);
//do something else
Sorry for the edit but here's another consideration. With each of these I obviously should check whether or not the connection was successful and throw an exception if it wasn't:
if (!$dbh) {
$err=$dbh->errorInfo();
throw new Exception('Could not connect: ' . $err[2]);
}
I don't suppose there's a way to avoid this, unless I create all the connections at the same time and do if (!dbh1|!dbh2) { ... }. Just something else to consider.
When you assign $dbh to a new PDO() you are not technically reusing your pdo object. You are creating a new PDO instance and assigning it to a variable that you have previously used. There is nothing wrong with doing this as long as you understand what is occurring in your program.
EDIT:
I'm editing my answer to address the new question you've added to your previous question.
With each of these I obviously should check whether or not the connection was successful and throw an exception if it wasn't:
You can surround your connection attempt in a try catch which is a typical strategy for dealing with connection errors:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=databaseName', $userName, $password);
foreach($dbh->query('SELECT * from TableName') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $ex) {
print "Error!: " . $ex->getMessage() . "<br />";
die();
}
?>
You can do that, but ... don't. Use another variable name (they are cheap) it will make your code much easier to understand. Heck you can (should) even use variable names that will clue you in on what database your object is connecting to, ie:
// connection to data warehouse
$dbh_dataWH = new PDO('mysql:host=' . $host . ';dbname=' . $db_name, $user, $password);
// connection to crm
$dbh_crm = new PDO('mysql:host=' . $host2 . ';dbname=' . $db_name2, $user2, $password2);
This way you will be able to re-use your connection objects, and the code in my very humble opinion will be much clearer for you or anyone else that has to maintain it.

Categories