Alex Briffett Life is just a state of mind

14Jan/100

PHP 5+ and MySQL 4.0 Could not connect

Hopefully you should never encounter this problem but I recently needed to do an insert into a MySQL 4.0 table from a remote installation of PHP 5.  I could connect from the PHP5 server to the MySQL 4.0 server via the command line, so assumed this would work find using PHP5.

I got the following error: Could not connect: Connecting to 3.22, 3.23 & 4.0 servers is not supported

Basically, later versions of PHP use a password encryption algorithm which means they are incompatible with MySQL 4.0 but not MySQL 4.1+.

Since the command line connection worked, the solution was to create a shell script on the PHP5 server which looked similar to the following:

#!/bin/sh

/usr/bin/mysql -u USERNAME -pPASSWORD DBNAME -h HOST<<STOP
insert into table (name, email) values ('$1','$2')
\g
STOP
exit

You will need to swap the capitalized variables for your own USERNAME, PASSWORD, DBNAME and HOST.

I called the shell script doinsert.sh and chmodded it 755 to make it executable.  Then, in my PHP script I used:

<?php

$r = shell_exec('./doinsert.sh ' . $name . " " . $email);

?>

...which executes the shell script and runs the insert statement I was aiming for. If you want to run a select statement instead of my insert example, then anything returned by the shell script should be available in $r.