DB-Verbindungen und Verwaltung der Verbindungen - mit PDO

tarifa

Lieutenant
Registriert
März 2020
Beiträge
549
Moin hallo Commuity

hier eine Frage zu Verbindungen und Verwaltung der Verbindungen - insbes. zur PDO-Basisklasse

vgl. https://www.php.net/manual/de/pdo.connections.php

Verbindungen werden durch das Erstellen von Instanzen der PDO-Basisklasse erzeugt. Es ist unerheblich, welchen Treiber Sie benutzen wollen. Sie benutzen immer den PDO-Klassennamen.
Der Konstruktor erwartet Parameter zur Angabe der Datenbankquelle (auch bekannt als DSN) und optional für Benutzername und Passwort (falls vorhanden).
Beispiel #1 Mit MySQL verbinden

Code:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>

Wenn es Fehler bei der Verbindung gibt, wird eine Ausnahme vom Typ PDOException geworfen. Sie können die Ausnahme abfangen, wenn Sie sich selbst um die Fehlerbedingung kümmern wollen, oder Sie können es einer globalen Routine zur Ausnahmebehandlung überlassen, die Sie mit set_exception_handler() konfigurieren.

Beispiel #2 Verbindungsfehler behandeln

Code:
?php
try {
   $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
   foreach ($dbh->query('SELECT * from FOO') as $row) {
      print_r($row);
   }
   $dbh = null;
} catch (PDOException $e) {
   print "Error!: " . $e->getMessage() . "<br/>";
   die();
}
?>


....also ich geh nochmals einen Schritt zurück zu einem Fehler: beim Installieren einer PHP Anwendung -( https://www.Limesurvey.org) auf einem Server ) der doch ganz stabil läuft und auf dem es im Grunde keine DB-Fehler(Verbindungsfehler) gibt.

Der Fehler:
Code:
 db-connection: SQLSTATE[HY000] [2002] No such file or directory
vgl. die Fehlerbeschreibung: https://forums.limesurvey.org/forum...-during-installprocess-what-to-do-here#208597

Hintergrund: Also das bedeutet dass php nicht den mysql.default_socket file finden kann. Ich denke dass ich hier mal ein paar Tests anstellen muss um zu sehen, ob ich zur mysql mittels pdo Verbindung herstellen kann.

Code:
try{
    $dbh = new pdo( 'mysql:host=127.0.0.1:3308;dbname=axpdb',
                    'admin',
                    '1234',
                    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
    die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}


....ist die Frage ob ich hier display errors off gleich noch brauche & das exception-Handling?

Hier noch eine weitere Version:
Code:
$host     = "localhost";//the type of our database, in this case my host machine    - well it is possible to use mysql:host=127.0.0.1:3308;dbname=axpdb',
$user     = "root";    //here we need the Username to use the database
$pass     = "qwerty123xyz";// here the password for that user
$dbname   = "DB";//Name of the corresponding database
$port = "3306";
$charset = 'utf8mb4';

try {
    $connection = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}catch(PDOException $e)
{
  echo $e->getMessage();                        
}

mir oder ohne error-handling .... hier mit:


Code:
<?php
$host     = "localhost";// the type of our database, in this case my host machine    - well it is possible to use mysql:host=127.0.0.1:3308;dbname=axpdb',
$servername = "localhost";
$username = "username";//here we need the Username to use the database
$password = "qwerty123xyz";// here the password for that user
$port = "3306"; //here we need the port
$charset = 'utf8mb4';// the charset is pretty important!

try {
  $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>


wie auch hier...:

Code:
$host     = "localhost";// the type of our database, in this case my host machine    - well it is possible to use mysql:host=127.0.0.1:3308;dbname=axpdb',
$servername = "localhost";
$username = "username";//here we need the Username to use the database
$password = "qwerty123xyz";// here the password for that user
$port = "3306"; //here we need the port
$charset = 'utf8mb4';// the charset is pretty important!

try {
    $connection = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}catch(PDOException $e)
{
  echo $e->getMessage();                        
}


für ein Array mit PDO hier die einzelnen Teile:

PDO::ATTR_ERRMODE - wichtig - immer auf PDO::ERRMODE_EXCEPTION. Es soll immer ein Error rauswerfen wenns nicht geklappt hat wenn es zu einem Fehler kommt mit mysql_query()
PDO::ATTR_EMULATE_PREPARES - diese Option zeigt ob PDO entweder einen emulation mode verwendet oder eben nicht.
PDO::setAttribute() method, turned off by default als eine Verbindungsoption
PDO::ATTR_DEFAULT_FETCH_MODE - Eine Komfort-Option. Obwohl die fetch method immer im fetch function call (wie etwa hier $row = $stmt->fetch(PDO::FETCH_ASSOC);) läuft - sind dies die beliebteste Fetch-Modes:
PDO::FETCH_ASSOC and PDO::FETCH_OBJ welches PDO veranlasset die Ergebnisse als Reihen zu holen - als assozotatives array oder als ein Objket


Vorhaben: ich werde jetzt mit dem Script testen wie die Verbindung via PDO zur DB aufgenommen wird.
 
Zuletzt bearbeitet:
Hallo und guten Abend deineMudda.


vorweg: vielen Dank für deine Rückmeldung über die ich mich sehr freue. Ich hab halt voll die Frage was es noch sein könnte.

dieser
Thread hier -
https://forums.limesurvey.org/forum...-during-installprocess-what-to-do-here#208597
da denke ich. ist das unbed. meine Servereinstellung oder kann das ggf auch noch daran liegen dass ich ggf. in dem LimeSurvey noch was besser anpassen sollte - also ggf. nach einem Workaround in dem LimeSurvey-Script suchen welcher mir erlaubt um diese dämliche (sorry) Installationsroutine zu kommen!?

Siehst du - deineMudda - da ggf. eine Möglichkeit. Das Interessante ist - alles was auf dem Server noch läuft - (z.B. Wordpress ) lässt sich einfach installieren - da ist es nie ein Problem die Verbindung zur DB herzustellen... !

Nur bei dem Limesurvey hab ich diese Socket_Probleme.

ich werde mir das von dir verlinkte nochmals genau durchlesen und durcharbeiten
 
Ich hatte da auch mal Probleme damit. Wenn der Server unter Unix läuft, dann kann es Probleme beim Verbindungsaufbau geben. Versuch es dann mal mit dem charset UTF8 und einer der folgenden DSN:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
Quelle:
https://www.php.net/manual/en/ref.pdo-mysql.connection.php

Kann mich leider nicht mehr erinnern, welche Lösung die richtige war, glaube aber der socket. Letztendlich solltest du dir funktionierende Beispiele anschauen, das ist oft besser als die PDO Dokumentation (leider):
Beispiel Laravel Framework: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Connectors/MySqlConnector.php
 
  • Gefällt mir
Reaktionen: tarifa
Hallo und guten Abend

vielen Dank für Deine Rückmeldung. Freue mich von dir zu hoeren. Also ich hab damit doch erhebliche Probleme. Hatte die vor einem Jahr bereits schon einmal - dann allerdings hatten wir hier eine Lösung. Nun - nach einem Serverupgrade (also neuer HW usw. usf.) geht das mit genau diesem speziellen Skript (Limesurvey) diesbezüglich wieder von vorne los. Aber ich bin weiter am Testen.

Der Server läuft auf OpenSuse - aber ich bin ziemlich sicher, dass wir hier die von dir beschriebenen Probleme haben.

Werde mal weitersuchen und melde mich wieder - um zu berichten.

Dir nochmals vielen Dank für deine Hinweise u. Tipps.

Vg Tarifa,


Nachtrag: Bei dem Script Limesurvey klemmt es hier tatsächlich immer wieder. Ich hatte mal denselben Error - vor einem Jahr - nun im Moment weiß ich leider nicht mehr welchen Workaround ich damals eingesetzt habe :

Der Thread hier - und darüber hinaus noch diverse andere zeigen - wie weit das Problem mit LimeSurvy dann doch geworden ist.

vgl hier https://forums.limesurvey.org/forum...-during-installprocess-what-to-do-here#208597

vgl. aber auch hier limesurvey
https://forums.limesurvey.org/forum/installation-a-update-issues/102836-database-connection-issue

I have been advised by my host that there are some variables in PHP v5.5 that are not compatible with LimeSurvey and that this was the cause of the installation issue.. And so we have changed the PHP to v5.3 and the installation has proceeded successfully. As I have other applications running on the server that require a higher version of PHP i may have to find another host for LimeSurvey.

PDO is a PHP native functionality today... so...
Again, many people are using LimeSurvey with PHP 5.5 without problem. The problem come from your host configuration, and your host provider should resolved it.
Here, a post of someone who experienced a similar problem :
www.limesurvey.org/en/community-services...-pdo-library-missing

Am advised the PDO database driver required for the application has a compatibility issue with php version 5.5. and higher. Host advises that their engineers are working on it.
Maybe that could help you.

PDO is a PHP native functionality today... so...
Again, many people are using LimeSurvey with PHP 5.5 without problem. The problem come from your host configuration, and your host provider should resolved it.

Here, a post of someone who experienced a similar problem:

https://www.limesurvey.org/en/commu...e-installation-checks-php-pdo-library-missing


I've copied all files to /limesurvey/ on my local server but when I go to /limesurvey/index.php it loads the first two screens and begins pre-installation checks. The screen tells me that "PHP PDO library" is "Not found".
I've copied the php.ini file to the base folder and enabled the extensions. (JSON and mbstring extensions where recognised before I did this) Is there something simple I haven't done as I don't have problems with other sites using the current php.ini settings

PDO is furnished with PHP since php 5.1
PHP 5.3 is the minimum required for LimeSurvey.

Yes I know that. I have PHP5.5.24 installed with php.ini file located in the base directory of limesurvey . The installer is not recognising it while it recognises mbstring and others required.


Ok, so basically, you resolved the problem- I'd say it must come from your server configuration. PDO should be available with any version of PHP superior to 5.1. Also, we could add a check for PDO like we're doing for other libs, but that would be to cover some exotic server configurations...

Whatever : thank you for reporting.

Sorry Louis I may not be expressing myself correctly. I still have the error. I cannot install Lime Survey because the pre-checks say that 'PHP PDO library' is not found when it is installed with PHP5.5. What I'm asking is, has anyone had the problem or know how to fix it? I'm stumped! I've tried searching the web, forums and IRC for clues to what might cause the installer to not recognise what is there. So far I have had no success at correcting the problem. I've removed the ';' from the php.ini file but the installer refusing to recognise it.
Found the problem. Server was pointing at the wrong php.ini file. My error!


Ende des Zitat wie man sieht steckt da mühsam mit der Arbeit beginnen. Doch in dieser Corona-Zeit sind alle
besonderen kulturellen Aspekte jetzt bestätigt. Das alles was ihr macht - das iat sehr sehr schön


freu mich nochmals von euch zu hoeren

update: wie vielfältig und wie zentral die Probleme hier sein können - bei der Installation von LimeSurvey zeigen diese wenigen Auszüge:

etwa dieser Thread hier https://forums.limesurvey.org/forum...-during-installprocess-what-to-do-here#208597

limesurvey https://forums.limesurvey.org/forum/installation-a-update-issues/102836-database-connection-issue
I have been advised by my host that there are some variables in PHP v5.5 that are not compatible with LimeSurvey and that this was the cause of the installation issue.. And so we have changed the PHP to v5.3 and the installation has proceeded successfully. As I have other applications running on the server that require a higher version of PHP i may have to find another host for LimeSurvey.

PDO is a PHP native functionality today... so...
Again, many people are using LimeSurvey with PHP 5.5 without problem. The problem come from your host configuration, and your host provider should resolved it. Here, a post of someone who experienced a similar problem https://forums.limesurvey.org/forum...e-installation-checks-php-pdo-library-missing

Am advised the PDO database driver required for the application has a compatibility issue with php version 5.5. and higher. Host advises that their engineers are working on it. Maybe that could help you.


PDO is a PHP native functionality today... so...Again, many people are using LimeSurvey with PHP 5.5 without problem. The problem come from your host configuration, and your host provider should resolved it.

Here, a post of someone who experienced a similar problem:

https://www.limesurvey.org/en/commu...e-installation-checks-php-pdo-library-missing

I've copied all files to /limesurvey/ on my local server but when I go to /limesurvey/index.php it loads the first two screens and begins pre-installation checks. The screen tells me that "PHP PDO library" is "Not found".
I've copied the php.ini file to the base folder and enabled the extensions. (JSON and mbstring extensions where recognised before I did this) Is there something simple I haven't done as I don't have problems with other sites using the current php.ini settings


PDO is furnished with PHP since php 5.1
PHP 5.3 is the minimum required for LimeSurvey.

Yes I know that. I have PHP5.5.24 installed with php.ini file located in the base directory of limesurvey . The installer is not recognising it while it recognises mbstring and others required.


Ok, so basically, you resolved the problem ?
I'd say it must come from your server configuration. PDO should be available with any version of PHP superior to 5.1. Also, we could add a check for PDO like we're doing for other libs, but that would be to cover some exotic server configurations...

Whatever : thank you for reporting.

Sorry Louis I may not be expressing myself correctly. I still have the error. I cannot install Lime Survey because the pre-checks say that 'PHP PDO library' is not found when it is installed with PHP5.5. What I'm asking is, has anyone had the problem or know how to fix it? I'm stumped! I've tried searching the web, forums and IRC for clues to what might cause the installer to not recognise what is there. So far I have had no success at correcting the problem. I've removed the ';' from the php.ini file but the installer refusing to recognise it.

Found the problem. Server was pointing at the wrong php.ini file. My error!

ich werde mal weitersuchen...
 
Zuletzt bearbeitet:
Die Links zu den Foren sind von anno dazumal, da wurde noch PHP 5 genutzt. Das aktuelle LimeSurvey benötigt mindesten PHP 7. Oder nutzt du wegen Lizenzen noch PHP 5? Ist das geforderte MySQL 5.5.3 oder höher installiert? Ist PDO denn als aktiv gelistet, wenn du phpinfo() aufrufst?

tarifa schrieb:
Das Interessante ist - alles was auf dem Server noch läuft - (z.B. Wordpress ) lässt sich einfach installieren
Und du hast auch mal exakt sie selben Zugangsdaten versucht?
 
  • Gefällt mir
Reaktionen: tarifa
Hallo und guten Abend Darlis

- danke für die Antwort. Also ich hab natürlich PHP 7 hier am Start. und es ist auch ein den Mindestanforderungen angemessenes (neueres) MySQL installiert. PDO ist als aktiv gelistet. Mit den Zugangsdaten die auch bei den WP laufen - die hab ich auch schon verwendet.

Zu den Links zu den LimeSurvey-Threads; ich habe den Eindruck dass hier bei LimeSurvey solche DB-Probleme immer wieder vorkommen. Ich muss noch gucken ob ich denn hier auf dem Server alle diesbezüglichen Anforderungen auch umgesetzt hab.


Ich werde mal weitersuchen - und berichte hier wieder.

vg; Tarifa
 
Zurück
Oben