Month: September 2008

PHP and MySQL in Tomcat with Quercus

Posted on Updated on

I was recently shown Quercus which is the PHP 5 engine implemented in pure Java and hence, can run in a servlet engine like Tomcat. Caucho suggest running it in Resin but for work reasons, I needed to get it running in Tomcat.

It was very easy to get PHP working, but the MySQL integration took a bit more figuring out. All the info I could find on the web assumed you knew all about DBs in Tomcat and didn’t seem to spell it out.

So here is what I did to get it running in Tomcat 6.0

Add the required jars to tomcat’s lib directory

  1. mysql-connector-java-5.1.5-bin.jar (from mysql’s download page)
  2. quercus.jar (in the quercus zip from caucho)
  3. resin-util.jar (in the quercus zip from caucho)
  4. script-10.jar (in the quercus zip from caucho)

Add the database to tomcats context.xml file

<Resource name="jdbc/mydatabasehandle" auth="Container"

Note: the jdbc url is all one line (up to mysqlEncoding=utf8) but is wrapped by the blog layout.
Note: Those really are &amp; (ampersand A-M-P semicolon). They are passed into the JDBC driver, and it must then convert html chars into text.

Add Quercus support to your web.xml

The quercus zip has an example web.xml file. These pieces below are mostly based on that.
<servlet-name>Quercus Servlet</servlet-name>
<!-- Tells Quercus to use the following JDBC database
and to ignore the arguments of mysqli_connect(). -->
<!-- tell tomcat about .php files -->
<servlet-name>Quercus Servlet</servlet-name>
<!-- tell tomcat about my php file called "myscript" (no extension)
so that URLs like /myscript/somepath will get "/somepath"
in php's $_SERVER["PATH_INFO"] variable. -->
<servlet-name>Quercus Servlet</servlet-name>

Use mysql in your PHP code

$dbh = mysqli_connect();
if ($result = mysqli_query($dbh, $sql)){
while ($row = mysqli_fetch_object($result)){
print $row->fieldName;

Other useful bits and pieces

  • Note the use of the mysqli methods. I was not successful in getting the plain old mysql commands to work.
  • $request is the java request object, so you can do stuff like $request->getUserPrincipal() if you are doing authentication in Tomcat like I was.