KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Ways to connect to 4D database using PHP
PRODUCT: 4D | VERSION: 13.3 | PLATFORM: Mac & Win
Published On: December 10, 2013

If PHP is your choice of scripting language to communicate with servers then it is possible to communicate with 4D databases. There are two ways that you can communicate with 4D using PHP by either using the PDO_4D driver or 4D ODBC driver. The PDO_4D driver implements the PDO (PHP Data Objects) interface to help developers write PHP code with given functions from the driver which accesses the 4D database. As for the 4D ODBC driver, it allows the PHP developers to use the standard PHP OBDC function calls to access the 4D database.

In order to use PDO_4D or 4D OBDC driver with PHP, the following items are required:

• A database running using 4D or 4D Server with version 13 or higher with the SQL Server running.

• A web server that supports PHP, such as Apache or IIS.

• PHP version 5.2.0 or higher with modules mbstring.

• (For PDO_4D driver) PDO 1.0.0 or newer. Download Driver
(To setup the PDO_4D driver, please refer to this Tech Note.)

• (For 4D ODBC driver) 64 bit driver version 13.3. Download Driver
To setup the 4D ODBC driver, please refer to this Link.


Please note: The 4D database does not need to be run on the same machine as Apache web or IIS
server.

Here is a sample PHP code that can assess the 4D database using PDO_4D driver:

<?php
$dsn = '4D:host=localhost;port=19812;charset=UTF-8';
$user = 'Administrator';
$pswd = 'test';
$db = new PDO($dsn, $user, $pswd);
$db->exec('CREATE TABLE IF NOT EXISTS myTable(id INT NOT NULL, value
VARCHAR(100))');
unset($db);
echo 'done'; // if you see this then the code ran successfully
?>



Here is a sample PHP code that accesses the 4D database using 4D ODBC driver:

<?php
$dsn = 'dsnName'; //DSN created by the 4D ODBC driver
$user = 'username';
$pswd = 'password';
$name ='Joe';
$conn = odbc_connect($dsn,$user,$pswd);
$sql_text = "INSERT INTO Customers(Name) VALUES('".$name."')";
$sql = odbc_prepare($conn,$sql_text);
$res = odbc_execute($sql);
echo $res; // if you see this then the code ran successfully
?>



Summary:

The PDO_4D and 4D ODBC drivers are the key to making the connection to the 4D server. If one uses the PDO_4D approach, it requires more steps to setup than the 4D ODBC. Another point to make is once the 4D ODBC driver is setup, the PHP function "odbc_connect" does not need to specify Ip Address, Port, and character set unlike PDO_4D. Either approach gives the developer options to connect to 4D.