Von einer Sommerpause fehlt am Horizont über Kiel jede Spur wie auch von einer schattenspenden Wolke. Heute berichtet der PHP Blog "PHP hates me" vom integrierten PHP mysqlnd Anfrage-Zwischenspeicher: Das MySQL Mofa. Der Artikel wiederholt bereits bekannte Grundlagen. Wer das "mysqlnd query result cache plugin" noch nicht kennt und wissen möchte wie alle PHP MySQL Erweiterungen um einen Anfrage-Zwischenspeicher erweitert werden können, der sollte einen Blick riskieren.
Neue und weitergehende Einblicke verschaffen die in den letzten Wochen veröffentlichten Präsentationen auf über 200 Vortragsfolien.
Es wird eine Weile dauern bis die Vortragsfolien in die reguläre Dokumentation eingearbeitet sind. Die erste Fassung der regulären Dokumentation wurde Ende letzter Woche fertiggestellt. Gerade noch rechtzeitig vor der ersten Erstellung eines PECL-Paketes. Die Query Cache Erweiterung zieht in diesen Tagen von der noch gültigen Projektseite unter http://forge.mysql.com/wiki/MySQLnd_Query_Cache_Plugin_for_PHP um auf PECL. Der Quellcode wurde bereits dem PECL-SVN-Archiv hinzugefügt, eine 1.0.0 getaggt, ein Paket hochgeladen und neue Funktionen wurden hinzugefügt. Trotz der Hitze ist das Projekt nicht ausgedörrt. Eine Sommerpause wird es kaum geben.
Das erste öffentliche PHP mysqlnd-Plugin ist da ! Das "mysqlnd query result plugin" (PHP-Lizenz - Quellcode) erweitert die Funktionalität aller PHP MySQL Schnittstellen (ext/mysqli, ext/mysql, PDO_MySQL) um Anfragecaching. Das Plugin kann Anfrageergebnisse im Hauptspeicher, in Memcached, APC und in SQLite (mit Wrapper auch BerkeleyDB) ablegen. Damit integriert es sich in etablierte Open Source Standardlösungen.
The first public mysqlnd plugin adds client side query result caching to all MySQL extensions of PHP (ext/mysql, ext/mysqli, PDO_MySQL). The cache is written in C. It does not change any of the PHP MySQL APIs and works with any PHP application using MySQL. Query results are stored on the client. Cached data can be stored in main memory, APC, Memcache, SQLite (theoretically - via SQLite wrapper - BerkeleyDB). The default invalidation strategy is TTL (Time to live): cache entries are valid for n-seconds. The TTL can be set per query or globally for all queries. User-defined storage handler can implement any invalidation method. Some built-in storage handler offer a special slam defense mode which you may know from Memcache or APC. Statistics help you to identify cache candidates and to measure cache efficiency. The plugin is available in source (PHP License)
C performance, almost transparent, horizontal scale out
The mysqlnd query result plugin is written in C like every other mysqlnd plugin today. It plugs into the MySQL native driver for PHP (mysqlnd) and adds query caching functionality to it. C gives you the best possible performance - better than any PHP based cache. The plugin is also a PHP extension. Adding a new PHP extension to an existing PHP deployment infrastructure should be easy going technically. Because it is a PHP extension and part of the database library, it gives many users, who do not compile PHP themselves, an "out-of-the box" experience. For those users caching will be just "built-in".
If you are new to mysqlnd and mysqlnd plugins, please note the background information given at the end of the article.
Any PHP MySQL application
|
ext/mysql, ext/mysqli, PDO_MySQL
|
MySQL native driver for PHP (mysqlnd)
mysqlnd query result cache plugin
Hit
Miss
Cache: main memory, Memcached, APC, SQLite
MySQL Server
The cache plugin operates on a new level in between the MySQL Server and the existing PHP MySQL APIs. Therefore it does not change any of the existing APIs. It works with every PHP MySQL application including existing ones. This is comparable to a proxy cache.
Pretty much exactly a year ago many german PHP meetups have held BBQs to celebrate the summer, to invite guests to join their meetups in a very relaxed atmosphere and to enjoy themselves. During the PHP BBQ week 2009 more than 140 people got connected and had fun . And, of course, I loved visiting all the meetups. I am not touring through the user groups this year. However, and that is fantastic news, some user groups have organized BBQs again. Today, June 22th - 19:00, you can enjoy a BBQ in Karlsruhe organized by the PHP user group Karlsruhe and sponsored by urlaubswerk.de! Check their homepage for the latest details.
KIT Campus Süd – Center für Innovation & Entrepreneurship (CIE)
CIE Cube – Geb. 30.29 Engesserstr. 9 (vor dem Gerthsen Hörsaal)
76131 Karlsruhe
I hear some rumors about Berlin but nothing seems decided yet or I am just uninformed… In any case, I strongly recommend to visit your local PHP user group to enjoy the events. Credits go to last and this years sponsors and the user groups which did it again!
If you hestitate visiting your local meetup, check the faces of the people which attended PHP BBQ 2009…
MySQL Proxy ist eine einzigartige und herausragende Software, die mit wenig Aufwand Probleme lösen kann, welche ansonsten nur mit massiven Änderungen an bestehenden Anwendungen gelöst werden könnten. Wie jeder Proxy eröffnet MySQL Proxy eine neue Schicht zwischen der Anwendung und der MySQL Datenbank. Die neue Schicht is klar getrennt von allen bestehenden, kann transparent agieren und verlangt damit keinerlei Änderungen an bestehender Infrastruktur.
Seit einigen Monaten ist in der PHP mysqlnd-Bibliothek von PHP 5.3 eine Alternative zum MySQL Proxy entstanden: mysqlnd plugins. PHP’s mysqlnd-Bibliothek kann von den PHP MySQ- Extensions (ext/mysql, ext/mysqli, PDO_MYSQL) als Alternative zur MySQL Client Library ("libmysql") verwendet werden. Seit PHP 5.3 ist mysqlnd ein Bestandteil des PHP-Quellcodes. mysqlnd implementiert das MySQL Client-Server Protokoll und stellt es mittels der MySQL C API den PHP-Extensions zur Verfügung. mysqlnd arbeitet somit innerhalb des PHP-Interpreters.
Drupal, phpMyFAQ, phpMyAdmin, Oxid, …
|
ext/mysql, ext/mysqli, ext/PDO_MYSQL
Mysqlnd
Mysqlnd plugin
Load Balancing
Monitoring
Performance
|
MySQL Server
Ähnlich dem MySQL Proxy agiert mysqlnd auf einer Schicht zwischen der Anwendung und der MySQL Datenbank. Unter Verwendung der mysqlnd Plugin API kann mysqlnd um neue Funktionalitäten erweitert werden. Damit ist es möglich clientseitige “Proxies” in Form von mysqlnd Plugins zu erstellen. Die mysqlnd Plugins können ähnliche Aufgaben übernehmen wie MySQL Proxy: Lastverteilung, Überwachung, Performanz bezogene Aufgaben.
Die unterschiedlichen Architekturen von MySQL Proxy und mysqlnd Plugins ergänzen und bereichern sich gegenseitig. Einige Limitation des MySQL Proxy können mit mysqlnd Plugins umgangen werden (kein Single-Point-Of-Failure, keine neue Programmiersprache mit Lua). Lesen Sie mehr dazu in den obigen Slides oder im ausführlicheren englischsprachigen Blogposting.
Rückmeldungen und Diskussionsbeiträge sind stets willkommen!
The mysqlnd plugin API is a well hidden gem of mysqlnd. Mysqlnd plugins operate on a layer between PHP applications and the MySQL server. This is comparable to MySQL Proxy. MySQL Proxy operates on a layer between any MySQL client application, for example, a PHP application and, the MySQL server. Plugins can take over classical MySQL Proxy tasks such as Load Balancing, Monitoring and Performance optimizations. But due to the different architecture and location mysqlnd plugins do not share some common MySQL Proxy annoyances: no single point of failure, no dedicated proxy server to deploy, no new programming language to learn (Lua).
Slides from the IPC Spring conference
This blog posting and today’s presentation at the IPC Spring 2010, a PHP conference in Berlin, are the first public
information on the new toy. Enjoy the slides or continue reading the blog posting.
A mysqlnd plugin is kind of an extension to mysqlnd. Plugins can hook virtually all mysqlnd functions. The mysqlnd functions are called by the PHP MySQL extensions (ext/mysql, ext/mysqli, PDO_MYSQL). Consequently it can be said that a mysqlnd plugin can hook all PHP MySQL userspace functions.
Internal mysqlnd function calls cannot only be hooked but also be replaced. There are no limits for manipulating mysqlnd internal function tables: maximum freedom!
Drupal, phpMyFAQ, phpMyAdmin, Oxid, …
|
ext/mysql, ext/mysqli, ext/PDO_MYSQL
Mysqlnd
Mysqlnd plugin
Load Balancing
Monitoring
Performance
|
MySQL Server
Plugins operate on the C level inside PHP and mysqlnd. They can be made 100% transparent to PHP applications. No application changes are needed because plugins operate on a different layer. A mysqlnd plugin adds a new layer to your setup. However, the new layer is part of a software you already deploy: PHP! A mysqlnd plugin is just another PHP extension in your existing PHP infrastructure.
Load Balancing
Read/Write Splitting
Failover
Round-Robin, least loaded
Monitoring
Query Logging
Query Analysis
Query Auditing
Performance
Caching
Throttling
Sharding
Mysqlnd plugins are a different technology than MySQL Proxy. Both are valid tools for solving a variety of common tasks ranging from Load Balancing over Monitoring to Performance. Both have their room, their disadvantages and advantages. An obvious difference: MySQL Proxy works with all MySQL Clients whereas mysqlnd plugins are specific and limited to PHP.
mysqlnd plugin vs. MySQL Proxy: architecture
A mysqlnd plugin gets installed on the PHP application server. MySQL Proxy can either be run on the PHP applications server or be installed on a dedicated machine to handle multple PHP application servers.
Deploying a proxy layer on the application machines has two advantages:
no single point of failure
easy to scale out (horizontal scale out, scale by client)
MySQL Proxy is a wonderful and unique piece of software. MySQL Proxy (and mysqlnd plugins) can solve problems easily which otherwise would have required massive changes to existing applications. But MySQL Proxy comes at a price:
MySQL Proxy is a new component and technology to master and deploy
MySQL Proxy Lua scripts are not PHP: Lua is a new additional language
MySQL Proxy can be customized with C and Lua programming. Lua is the preferred scripting language of MySQL Proxy. For most PHP experts Lua is a new language to learn. A mysqlnd plugin can be written in C (or PHP - as will be shown in future blog posts). C and PHP should be a natural fit for your existing man power and teams.
Hardware
Software
Application server
PHP application
C/Java/PHP/… application
mysqlnd plugin
MySQL Proxy
Dedicated machine
MySQL Proxy
Database server
MySQL
Lifecycle: deamon vs. PHP lifecycle. MySQL Proxy is a deamon. It runs forever. MySQL Proxy can recall earlier decisions. A mysqlnd plugin is bound to the PHP lifecycle of one or multiple web requests. MySQL Proxy can share once computed results among multiple application server. To do the same a mysqlnd plugin needs to store its knowledge in a persistent medium, for example, using another daemon such as Memcache. MySQL Proxy has the edge.
mysqlnd plugin: choose C API or wire protocol
MySQL Proxy works on top of the wire protocol. With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol. Actions are limited to what can be done by manipulating the communication protocol. If the wire protocol changes, which happens very rarely, MySQL Proxy scripts need to be changed as well.
Layer
Software
PHP application
C/Java/PHP/… application
C API
mysqlnd plugin
Wire protocol
mysqlnd plugin
MySQL Proxy
Mysqlnd plugins work on top of the C API (and thus also on top of the wire protocol). You can hook all C API calls. PHP makes use of the C API. Therefore you can hook all PHP calls. There is no need to go down to the level of the wire protocol.
Mysqlnd implements the wire protocol. Plugins can parse, reverse engineer,manipulate and even replace the communication protocol. However, there are few use cases which require you to work on this low level.
b>Mysqlnd plugins usually operate the C API layer but they can, if need be, operate on the wire protocol as well..
Plugins let you do your manipulations on two layers: C API and wire protocol. This is more than what MySQL Proxy has to offer. Wire protocol changes do not require plugin changes.
Get the mysqlnd plugin API today!
If you have recently downloaded a PHP 5.3 development code snapshot you already downloaded the "mysqlnd plugin API". No, there is no downloadable mysqlnd plugin which gives you all the fabled features sketched above. The mysqlnd plugin API is under development since at least christmas 2009. It is developed in the PHP source repository and available to public.
The "mysqlnd plugin API" has its roots in the ancient history of mysqlnd. It is a bit of a side effect of Andrey’s attempt to modularize the more than 15k loc of mysqlnd. It took us some time to realize the potential of Andrey’s changes. But this is another story, this is for another blog posting.
Like it? More blogging to come
Several companies have expressed severe interest in the mysqlnd plugin idea after todays presentation at the IPC Spring. If you see some potential in the new toy, please drop us a note. You can reach Andrey, me and Johannes through the usual channels.
More blog postings will follow describing more and more aspects of the new toy. Ideally we manage to teach you how to hack your own mysqlnd plugins - start your GCC’s boys!
Background: mysqlnd is a libmysql replacement
The MySQL native driver for PHP (mysqlnd) is a C library which implements the MySQL Client Server Protocol. It serves as a drop-in replacement for the MySQL Client Library (AKA libmysql AKA libmysqlclient AKA Connector/C). mysqlnd is also a special kind of a PHP extension. Similar to ext/PDO it does not export any userland functions. It serves as a C library for other extensions.
mysqlnd is part of the PHP source code repository as of PHP 5.3. Every PHP source code distribution contains it.
Server API (SAPI)
CGI
CLI
Embed
ISAPI
NSAPI
phttpd
thttpd
…
Zend Engine
PHP Runtime
PHP Extensions
bcmath
mysql
mysqli
mysqlnd
pdo
pdo_mysql
xml
…
All PHP-MySQL APIs can either make use of the MySQL Client Library or mysqlnd to connect to MySQL. The decision to use one or the other library is made at compile time. Within a PHP binary you can mix mysqlnd and the MySQL Client Library as you like: one PHP MySQL API may use mysqlnd and another PHP MySQL extension may use the MySQL Client Library.
To use the MySQL Client Library, you must have it installed on your system (at least when building PHP), whereas mysqlnd ships with PHP and thus has no pre-requisites.
Seit einigen Monaten ist es möglich, mysqlnd plugins zu schreiben. Seit einigen Minuten gibt es die notwendigen Informationen dafür online für all diejenigen, die RSS-Feeds anstelle von Kommentardateien (*.c) lesen.
mysqlnd plugins sind eine Art Proxy, eine Art Erweiterung , die auf einem neuen Layer zwischen der PHP-Anwendung und der MySQL-Datenbank arbeiten. Sie können transparent agieren für eine PHP-Anwendung - wie MySQL Proxy. Sie können Load Balancing, Monitoring oder Performance-Lösungen bieten - wie MySQL Proxy. mysqlnd plugins verlangen kein Lua. mysqlnd plugins sind kein Single-Point-of-Failure.
Mehr dazu in den Materialien unten, die erstmals vor zwei Stunden auf der IPC Spring in Berlin präsentatiert wurde. Mehr dazu in den nächsten Tagen auf diesem RSS-Feed.
Gelesen: Expert PHP and MySQL, Zielgruppe: Fortgeschrittene und Experten
Wertung und Fazit: 4/5 - sein Geld wert. Nicht mehr, nicht weniger.
Ein guter Consultant, der für sein aktuelles und breit gestreutes Expertenwissen bezahlt wird, drückt in kürzester Zeit viel Wissen in die Köpfe der Angestellten. Er führt eine "Druckbetankung" durch. Dieses Buch ist von wohlbekannten Beratern und Entwicklern verfasst worden, die ähnliches mit dem Leser machen.
Experten, die einen schnellen Überblick über die zum Zeitpunkt des Erscheinens aktuellen Expertenthemen zur Backend-Entwicklung mit PHP und MySQL suchen, werden in diesem Buch fündig. Das breite Themenspektrum gibt die offizielle Buchbeschreibung wieder.
Der eine freut sich über die Wiederholung von Transaktionen und dem Schlagwort “ACID”, den Darstellungen verschiedener Spielarten von Verbünden (JOINs) und anderen Einsteigerthemen in den Einführungskapiteln. Der nächste freut sich über eine der ersten Darstellungen wie in C geschriebene PHP-Erweiterungen Namespaces nutzen können. Und, vielleicht, freuen sich beide Leser über die ersten Praxisbeispiele zu MySQLs-UDFs, die ihnen bislang entgangen waren.
Am Ende des Buches und am Ende eines Beraterbesuches angekommen folgt unweigerlich die Zusammenfassung und die Reflektion.
Neben einigen kleineren Fehlern (z.B. PHP C-API - Buch und falsch: RETURN_TRUE() vs. korrekt: RETURN_TRUE, oder: uint64 -> sprintf(”%d”, …)) in der ersten Auflage steht für mich ein bisweilen wilder aber dennoch interessanter Cocktail aus aktuellen Themen.
In keinem Bereich liefert das Buch genug Tiefe, um auf fortführende Lektüre verzichten zu können. Das Buch ist somit kein Klassiker. Es ist eine Momentaufnahme - ein kurzer Besuch eines Beraters. Glücklicherweise ist das Buch weit preiswerter als ein Berater und hält auch Respektsabstand zu den Buchpreisen, die für manch einen Buchklassiker aufgerufen werden.
Wertung und Fazit: 4/5 - sein Geld wert. Nicht mehr, nicht weniger.
Trotz des denkwürdigen Datums wurde gestern Nacht der Ticketverkauf für die PHP Unconference 2010 eröffnet. Ich kann nur jedem zur Eile raten, um sich eines der wenigen Tickets für diese "Pflichtveranstaltung" zu sichern. Letztes Jahr waren die meisten Tickets binnen weniger Tage vergriffen.
PHP Unconference Hamburg 2010
25.-26. September 2010
Hamburg, Universität, Geomatikum
Für mich ist die Unconference zum PHP-MySQL-Ereignis des Jahres avanciert. Für den Ticketpreis von 30,– Euro gibt es ein zweitägiges Stelldichein der Who-Is-Who der PHP-Szene mitsamt Wissens-Druckbetankung. Anders als in den Vorjahren werde ich diesmal dem Motto "Zugeschaut und mitgebaut" folgen und einige Vorträge vorschlagen. Ob diese gehalten werden entscheiden die Teilnehmer zu Beginn der Veranstaltung. Es ist eine Unconference.
Wer etwas in meinem Blogarchiv blättert, wird an den Berichten der letzten Jahre sehen, daß meine Begeisterung nicht vorgetäuscht ist.
Die letzten Wochen brachten einen neuen Rang: Knipser.
Seit zwei Tage gelten neue Regeln für Blogpostings, welche sich auf Arbeit beziehen. Das Kleingedruckte enthält Anweisungen, die mein Blogverhalten verändern werden.
Nach einem fast einjährigem Umweg über den MySQL Connector/OpenOffice.org und MySQL Connector/C++ arbeite ich derzeit wieder an mysqlnd (MySQL native driver for PHP). Die Implementierung des MySQL Client-Server-Protokolls ist weitestgehend abgeschlossen. Wir experimentieren mit verschiedenen Ideen. Vereinzelt vergreife auch ich mich an den ".c"-Dateien - sehr zum Leid von Andrey. Mehr mag ich zur Arbeit nicht sagen.
Derweil vergnügt sich der elePHPant im Winter-Wunderland. Seine Lebensfreude ist ansteckend. Wenn er einmal nicht das Model aus der Kälte spielen will, müssen die für Flickr obligatorischen Blümchenbilder herhalten. Vielleicht sollte ich eine elePHPant-Model-WG eröffnen, um seine Karriere zu fördern…
Die 7 ist eine aufregende Zahl. Heute ist Sonntag. Der siebte Tag in der Woche. Zwei mal sieben ist 14. Vor 14 Jahren wurde mir die staatliche Erlaubnis erteilt motorisierte Zweiräder mit einer Leistung von fast fünf mal sieben Pferdestärken zu fahren. Etwa siebzehn Monate lang ritt ich auf einer Gummikuh, einer Strich 7, durch die Lande, bis ein Ventilabriss die Reise beendete. Vor sieben Tagen jährte sich der Erwerb des Autoführerscheins, den ich seit zwei mal sieben minus eins Jahren erwarb, obwohl ich während der Fahrprüfung die Ohren eines parkenden Wagens touchierte.
In einem Peugeot 407 habe ich bei 30 mal sieben km/h die lebenswichtige Bedeutung eines Sicherheitskäfigs erfahren. Geschätzte 10 mal sieben km/h Geschwindigkeitsunterschied zum Vordermann ließen sich nicht schnell genug abbauen als dieser unverhofft die Spur wechselte.
Nach 37.000 km im eigenen PKW, sieben Jahren ohne eigenes Fahrzeug und 77.777 km in Mietwagen zurückgelegten Kilometern drohte meine KFZ-Schadenfreiheitsklasse in 07/2009 zu erlöschen. Aus diesem Grunde erwarb ich vor sieben Monaten einen sieben PS starken Roller dessen theoretische Höchstgeschwindigkeit über 77 km/h liegt. "Uwe, gibt mir was für die Versicherung - ich stell das Ding in den Keller nur der Versicherung wegen". Ich bin ein Lügner: sieben Monate, 7.000 km. Heute waren es 170 km. Früher habe ich das mit dem Fahrrad gemacht, früher…
C and PHP MySQL clients can set a connection timeout before a connection is established to MySQL. The MySQL C API manual states about MYSQL_OPT_CONNECT_TIMEOUT , which is equal to PHPs MYSQLI_OPT_CONNECT_TIMEOUT:
That is half of the story. The actual behaviour depends on the library you use, the operating system and the transport protocol (TCP/IP, Unix domain sockets, Windows named pipes, Shared Memory).
C users can choose between the MySQL Client Library, which ships with the MySQL server, and the MySQL Connector/C, a new standalone version of the client library. PHP users have a third library option. PHP users can also choose to use the MySQL native driver for PHP (mysqlnd). All three libraries create TCP/IP connections differently resulting in different behaviour.
This article focusses on PHP and TCP/IP. Nevertheless it may be a valuable read for C developers, because PHP itself is written in C. Therefore, PHP inherits all limitations of the underlying MySQL Client Library, just like any other C client.
Sometimes you forget about what you did years ago, for example the ability of mysqlnd write back traces of slow queries into the PHP error log . Regardless if you use mysqlnd with ext/mysql, ext/mysqli or PDO_MYSQL, mysqlnd is able to tell you which of your code has executed a slow query. To enable the feature, you need to compile PHP with CFLAGS="-D A0". A0? Yeah, we must have had some doubts about the usefulness.
Yes, 150 means we added some 30 performance statistics to the MySQL native driver for PHP (mysqlnd) since monday. The new statistics are explained in three words: counting COM_* commands. COM_* commands refers to the command packets of the MySQL client server protocol. For example, COM_QUERY is used to execute nonprepared SQL statements.
Please check the earlier blog postings on how to use and access the statistics: PHP: 59 tuning screws for mysqlnd, PHP: 120 tuning screws for mysqlnd. The information given in those articles will find its way into the PHP and MySQL manual. The MySQL documentation team is working on an update. But for now, an hour after the latest commit, you are requested to check the blog postings.
Es gibt drei Extensions mit deren Hilfe ein PHP-Skript auf einen MySQL Server zugreifen kann: ext/mysql, ext/mysqli und PDO_MYSQL. Alle drei sind geeignet, um die Entwicklungsgeschichte von PHP und MySQL Revue passieren zu lassen, alle drei sind geeignet, um Kopfschütteln oder Staunen hervorzurufen. Heute: Grundlagen des Verbindungsaufbaus mit ext/mysql - wie verbinde ich PHP mit MySQL?
Um zu beantworten was passieren wird, ist es notwendig das Betriebssystem, die verwendete Client Bibliothek und mindestens eine PHP-Konfigurationsdirektive zu kennen. Das Betriebssystem ergibt sich aus dem Beispiel: es ist ein Unix. Die verwendete Client Bibliothek ist MySQL Client Library (libmysql). Es ist ein Standardbuild, genauso wie PHP und MySQL unverändert aus der Tüte gefallen sind. Es wurden keine PHP-Konfigurationsdirektiven gesetzt und die Standardeinstellungen von PHP 5.3 werden benutzt.
Das Betriebssystem und die PHP-Konfigurationsdirektive mysql.default_port entscheidet darüber ob das Setzen der Umgebungsvariablen MYSQL_TCP_PORT einen Einfluß auf ext/mysql hat. Unter Windows oder Netware wird die Umgebungsvariable nicht ausgewertet. Im Beispiel wird ein Unix verwendet. Auf diesem System wird die Umgebungsvariable einen etwaigen “mysql” Eintrag aus der TCP-Sektion in /etc/services überstimmen, sofern kein Wert für mysql.default_port gesetzt ist, welches die Standardeinstellung ist. Ist das dokumentiert? Ja, in der php.ini-production findet sich eine Notiz. Dort wird auch die Bedeutung des Compile-Flags MYSQL_PORT erklärt.
Da als Hostname die IP-Adresse “127.0.0.1″ angegeben ist und der Port 3307 benutzt wird gemäß der Umgebungsvariable MYSQL_TCP_PORT, baut die MySQL Client Library (libmysql) eine TCP/IP Verbindung auf. Die Verbindung schlägt fehl, weil es sich beim MySQL Server um eine Standardinstallation handelt, die auf Port 3306 horcht. Der Fehler führt zu einer PHP Warnung die, je nach Wert der PHP-Direktive error_reporting, leicht übersehen werden kann: Warning: mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in Command line code on line 1.
Anschließend macht PHP unbeirrt weiter und der Aufruf von mysql_query() baut implizit eine neue Verbindung auf, weil - wie bei ext/mysql üblich und möglich - kein Handle angegeben wurde. Ja, das ist dokumentiert. Die Verbindung wird zum Host = NULL auf Port 3307 aufgebaut. Host = NULL findet Anwendung, weil kein Wert für die PHP-Konfigurationsdirektive mysql.default_host gesetzt ist. Eine leere Hostangabe bewirkt unter Unix in der MySQL Client Bibliothek einen Fallback auf localhost und Unix Domain Sockets. Auf Windows würde etwas anderes passieren.
Mit der Hostangabe localhost und mit dem Standardwert einer leeren PHP-Konfigurationsdirektive mysql.default_socket wird das Socket /tmp/mysql.sock verwendet. Aber auch nur, wenn es sich um einen Standardbuild von PHP handelt, PHP_MYSQL_UNIX_SOCK_ADDR nicht beim Kompilieren definiert wurde und es sich auch um einen Standardbuild der MySQL Client Library handelt. Ist das dokumentiert? Sicher, ich habe es doch hiermit gerade dokumentiert!
Schlußendlich gelingt es SELECT SLEEP(10) über einer Unix Domain Socket Verbindung an MySQL zu senden und das Skript wird nach etwa 10 Sekunden beendet. var_dump($link) gibt false aus, da der Verbindungsaufbau fehlgeschlagen ist. Hier noch einmal das korrekte und fehlerfreie Ergebnis im Überblick:
time MYSQL_TCP_PORT=3307 sapi/cli/php -r '$link = mysql_connect(\"127.0.0.1\", \"root\", \"root\"); mysql_query(\"SELECT SLEEP(10)\"); var_dump($link);'
Warning: mysql_connect(): Lost connection to MySQL server at 'reading initial communication packet', system error: 111 in Command line code on line 1
bool(false)
real 0m10.024s
user 0m0.008s
sys 0m0.004s
Alles gaaanz easy…. Und bloß nicht ext/mysqli verwenden. Das baut nicht implizit Verbindungen auf, unterbindet die Verwendung von Umgebungsvariablen, verhindert das Bauen von optimierten und angepassten Binaries mit verbesserten Standardeinstellungen, verlangt bei jedem Kommando die Angabe eines Verbindungshandle und unterstützt neben irrelevanten Dingen wie Prepared Statements auch noch performanzkritische C API Funktionen wie mysql_warning_count().