Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 10.0.1 » SQL Anywhere Server - Programming » SQL Anywhere PHP API » Writing PHP scripts

Writing PHP scripts Next Page

Connecting to a database

To make a connection to a database, pass a standard SQL Anywhere connection string to the database server as a parameter to the sqlanywhere_connect function. The <? and ?> tags tell the web server that it should let PHP execute the code that lies between them and replace it with the PHP output.

The source code for this example is contained in your SQL Anywhere installation in a file called connect.php.

  # Ensure that the SQL Anywhere PHP module is loaded
  if( !extension_loaded('sqlanywhere') ) {
    # Find out which version of PHP is running
    list($version, $rest) = explode('.', phpversion(), 2);
    $module_name = 'php'.$version.'_sqlanywhere10';
    if( strtoupper(substr(PHP_OS, 0, 3) == 'WIN' )) {
        dl( $module_name.'.dll' );
    } else {
        dl( $module_name.'.so' );
  # Connect using the default user ID and password
  $conn = sqlanywhere_connect( "UID=DBA;PWD=sql" );
  if( ! $conn ) {
      die ("Connection failed");
  } else {
      echo "Connected successfully\n";
      sqlanywhere_disconnect( $conn );

The first block of code verifies that the PHP module is loaded. If you added the line to your PHP initialization file to load it automatically, this block of code is unnecessary. If you did not configure PHP to automatically load the SQL Anywhere PHP module at start time, you must add this code to the other sample scripts.

The second block attempts to make a connection. For this code to succeed, the SQL Anywhere sample database must be running.