PHP & DBMaker

Table Of Contents

Chapter 1. PHP installation and settings

1.1 Introduction to PHP

1.2 Installation and settings of PHP Server

Installation

Chapter 2. PHP Syntax

2.1 Using PHP in HTML
2.2 Variables

Variable initialization
The scope of a variable

2.3 Getting user input values from the Browser

Use Post and Get statements
Use URL to pass parameter
Use Cookies

2.4 Data Types
2.5 Language structure

IF
Else
ELSEIF

IF(): ... ENDIF


WHILE

DO..WHILE

FOR

SWITCH
REQUIRE
INCLUDE

2.6 Functions

Return value
Function's parameters

2.7 Operators

Numerical operator
String operator

Boolean operator

comparison operator

Chapter3 . PHP+DBMaker

3.1 The procedures
3.2 Connecting to a database

ODBC_CONNECT
ODBC_CLOSE

ODBC_CLOSEALL

3.3 Transaction control

ODBC_AUTOCOMMIT
ODBC_COMMIT
ODBC_ROLLBACK

3.4 ExecuteSQL statements

ODBC_PREPARE
ODBC_EXECUTE

ODBC_EXEC
ODBC_DO

3.5 Extracting data

ODBC_CURSOR
ODBC_RESULT_ALL
ODBC_FETCH_INTO

ODBC_FETCH_ROW
ODBC_RESULT
ODBC_RUM_ROWS

ODBC_NUM_FIELDS

DOBC_FIELD_NUM

ODBC_FIELD_NAME

ODBC_FIELD_TYPE
ODBC_FREE_RESULT


PHP installation and settings

Introduction to PHP

Personal Home Page III, or PHP, is an embedded script language in HTML. PHP is installed in the server side, where the Web server is located. With php.exe, a script file written in PHP will be interpreted into a HTML file and sent to the user. The first version of PHP was published in the beginning of 1995, the second version was in the middle of 1995, and the latest version was in 1997, which is the current PHP. PHP is easy to learn and use so it has become popular for Web database application development. In March, 1999, the popularity of PHP is shown with Web database applications used in 409,418 Domains and 143,667 IP addresses. Security, file uploading, and HTTP cookies are supported in version 3.0 3.0. Furthermore, and most importantly, there are many well-known databases supported by PHP, including DBMaker, Oracle, Adabas D, Sybase, FilePro, mSQL, Velocis, MySQL, Informix, Solid, dBase, ODBC, Unix dbm, and PostgreSQL.

Installation and settings of PHP Server

Installation

PHP can be installed on Windows NT or any UNIX-based platform. With the following procedure, we will introduce only how to install in Linux running the apache web server. You can get the latest version of PHP from the Web http://www.php.net.

The installation procedure is as follows:

 1. gunzip php-4.0.x.tar.gz

 2. tar xvf php-4.0.x.tar

 2. cd ../php-4.0.x

 3. ./configure --with-dbmaker \

      --with-apxs=/usr/sbin/apxs \

      --enable-track-vars

 4. make

 5. make install



Make sure you shut down your server first though.



 6. cp php.ini-dist /usr/local/lib/php.ini



You can edit the /usr/local/lib/php.ini file to

set PHP options. If you prefer this file in another

location, use --with-config-file=/path in



 7. Edit your httpd.conf or srm.conf file and add:

AddType application/x-httpd-php .php



You can choose any extension you wish here. .php3 is

simply the one we suggest.

PHP Syntax

Using PHP in HTML

In this chapter, we will introduce how to write a first PHP program. Like ASP or JAVA, you can have a program segment written in PHP inside an HTML file. The program segment could be partially or all of the HTML file. Moreover, you need to remember to change the HTML file name as xxx.php, where the xxx is the name following the naming rules of the file system used. The php in the file name follows the setting in the installation (AddType application/x-httpd-php .php), normally we use .php.

In PHP, there are 4 ways to indicate a program is a PHP program as follows


1. <? echo("this is the simplest instruction\n");?>

2. <?php echo("if you want to serve XML documents, do it like this\n"); ?>

3. <script language="php">

   echo("some editors (like FrontPage) don't like processing

   instructions");

   </script>

4. <% echo("As of PHP 4.0 you may optionally use ASP-style tags"); %>
Variables

Variable initialization

In PHP, a variable exists with a data type when the variable is defined by an assignment statement. That means, you do not have to declare a variable before using it. for example:

initialize an array

$names[] = "Jill"; // $names[0]          = "Jill"

$names[] = "Jack"; // $names[1]          = "Jack"

initialize an object

class foo {

function do_foo() {

  echo "Doing foo.";

}

$bar = new foo;

$bar->do_foo();

The scope of a variable

Basically, a variable could be used only in the program or the function in which it is defined. But if you want, a variable could be used outside of the function in which the variable is defined by adding "global" at the front of the variable, or define the variable outside of all functions but in the same program. Some examples are shown as follows.

Example 1:Do not use global


$a=1; /* global scope */ 

Function Test() { 

  echo $a; /* reference to local scope variable, a is NULL */

} 

Test();

Example 2: Use global, the result of $b will be 3


$a=1; 

$b=2; 

Function Sum() { 

  global $a,$b; 

  $b = $a + $b; 

} 

Sum(); 

echo $b;

Example 3:Use $globals

$a=1;

$b=2;

Function Sum() 

  $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];

}

Sum();

echo $b;

You may need a static variable, for instance, in a loop. A static variable is initialized the first time it is used. For example, in a loop program as below, the variable "count" is defined as static by the statement "static $count=0". Then the variable "count" is only initialized the first time it is initialized and it will not be initialized again as the statement "static $count=0" is met.

Example:


Function Test() { 

  static $count=0; 

  $count++; 

  echo $count; 

  if($count < 10) { 

    Test(); 

  }

}
Getting user input values from the Browser

Use Post and Get
You can use PUT and GET to get the user input value in a CGI program. In a traditional CGI program written by C, the program for passing parameters is complex, but, in PHP, it is much easier because you use the same object name as the variable name, then you can easily get the input value.

Example

A form is designed as follows. The server side program submit.php will be started when the button submit is clicked. Then, the variable $text1 will get the user input value, where the variable "text1" is the same as the name of the object "text1" defined in the form.

(graphic)


<form method="post" action="submit.php" name="test_form">

<p>input value: 

<input type="text" name="text1">

</p>

<p>

<input type="submit" name="Submit" value="Submit">

</p>

</form>

Use URL to pass parameters

The following syntax is frequently seen in Web programs.

<A Href="show.php?sn=20&category=book">

Click here, you can see more detail</a>

          

With the same concept, use $sn, $category to get associated values from the above parameters.

Use Cookie

You can use the function "SetCookie" to store values in the client side. And use the same name as variable name to get the value of the Cookie.

SetCookie("TestCookie","Test Value");

SetCookie("TestCookie",$value,time()+3600); /* expire in 1 hour */

Notice: Because the Cookie belongs to the HTTP Header, it is necessary to use SetCookie at the top of the Web page content, otherwise the function will not work.

Data types

Normally, you have to declare the data type of a variable before using it, such as integer, string, float, double...etc. But in PHP, the data type of a variable is automatically declared as you assign a value to the variable.

Examples:


$foo = "0";        // $foo is a string (ASCII 48)

$foo++;            // $foo is the string "1" (ASCII 49)

$foo += 1;         // $foo is now an integer (2)

$foo = $foo + 1.3; // $foo is now a double (3.3)

You can force a variable to be a particular data type if you specify the data type at the front of the variable as in the following example


$foo = 10;            // $foo is an integer

$bar = (double) $foo; // $bar is a double

Available data types are as follows:

(int), (integer) - cast to integer

(real), (double), (float) - cast to double

(string) - cast to string

(array) - cast to array

(object) - cast to object

Language structure

IF

if (expr)

statement

Example 1

if ($a > $b)

  print "a is bigger than b";

Example 2


if ($a>$b) {

  print "a is bigger than b";

  $b = $a;

}

Else


if ($a>$b) {

  print "a is bigger than b";

} else {

  print "a is NOT bigger than b";

}

ELSEIF


if ($a > $b) {

  print "a is bigger than b";

} elseif ($a == $b) {

  print "a is equal to b";

} else {

  print "a is smaller than b";

}

IF():...ENDIF

HTML cannot be used in an IF statement without using echo. Or use IF(): !K ENDIF to add HTML. The example is as follows

Example 1: incorrect example

<?php if ($a==5){ ?>

  <font size=!¡L2">Welcome!</font>

<?php } ?>

Example 2: Correct example

<?php if ($a==5): ?>

  <font size=!¡L2">Welcome!</font>

<?php endif; ?>

          

WHILE

Syntax:

WHILE(expr) statement

WHILE(expr): statement ...

ENDWHILE;

Example 1:

$i=1;



while ($i<=10) {

  print $i++; /*Print $i, then add 1 to i*/

}

          

Example 2:


$i=1;



while ($i<=10):

  print $i;

  $i++;

endwhile;

          

DO..WHILE

Example 1:

$i = 0;



do {



  print $i;



} while ($i>0);

          

Example 2:

do {



  if ($i < 5) {

    print "i is not big enough";

    break;

  }

  $i *= $factor;

  if ($i < $minimum_limit) {

    break;

  }

  print "i is ok";

} while(0);

          

FOR

Syntax:

FOR (expr1; expr2; expr3) statement

The command FOR(expr): ... ENDFOR is not supported

Example 1:

for ($i=1; $i<=10; $i++) {

  print $i;

}

          

Example 2:

for ($i = 1;;$i++) {



  if ($i > 10) {

    break;

  }

  print $i;

}

          

Example 3:


$i = 1;



for (;;) {



  if ($i > 10) {

    break;

  }

  print $i;

  $i++;

}

          

SWITCH

Example 1: using IF

if ($i == 0) {



  print "i equals 0";

}

if ($i == 1) {

  print "i equals 1";

}

if ($i == 2) {

  print "i equals 2";

}

          

Example 2: Using switch

switch ($i) {



  case 0:



    print "i equals 0";

    break;

  case 1:

    print "i equals 1";

    break;

  case 2:

    print "i equals 2";

  break;

}

          

In PHP, the program will continue executing the next case in a switch statement unless "break" is used to jump out and execute the next statement after the switch statement.

Example 3:

switch ($i) {



  case 0:



    print "i equals 0";

  case 1:

    print "i equals 1";

  case 2:

    print "i equals 2";

}

When $i=0, it will print out "i equals 0 i equals 1 i equals 2"

When $i=1, it will print out "i equals 1 i equals 2"

When $i=2, it will print out "i equals 2"

Example 4:Using "Default" for the other conditions

switch ($i) {



  case 0:



    print "i equals 0";

    break;

  case 1:

    print "i equals 1";

    break;

  case 2:

    print "i equals 2";

    break;

  default:

    print "i is not equal to 0, 1 or 2";

}

          

REQUIRE

You can include a file in PHP, which is like #include in the C programming language, but the REQUIRE function cannot be used in a loop statement

Example:

require('header.inc');

INCLUDE

Similar to REQUIRE, but you can use it in a loop statement

Example:


$files = array('first.inc', 'second.inc', 'third.inc');



for ($i = 0; $i < count($files); $i++) {

  include($files[$i]);

          
Functions

You can define a function in PHP as follows:

function foo( $arg_1, $arg_2, ..., $arg_n ) {



  echo "Example function.\n";

  return $retval;

}

Return value

Example 1: Return a single value

function my_sqrt( $num ) {



  return $num * $num;



}



echo my_sqrt( 4 ); // outputs '16'

          

Example 2:Return multiple values

function foo() {



  return array( 0, 1, 2 );



}



list( $zero, $one, $two ) = foo();

          

Function's parameters

You can pass parameters to a function by "Passing by reference" and "Passing by value". The default is "Passing by value".

Example 1:Passing by reference

function foo( &$bar ) {

  $bar .= ' and something extra.';

}

$str = 'This is a string, ';

foo2( $str );

echo $str; // outputs 'This is a string, and something extra.'

          

Example 2:Passing by value

function foo( $bar ) {



  $bar .= ' and something extra.';



}



$str = 'This is a string, ';



foo2( $str );



echo $str; // outputs 'This is a string, '



foo2( &$str );



echo $str; // outputs 'This is a string, and something extra.'

          
Operators

Numerical operator

Operators

Example

Addition(+)

$a + $b

Subtraction(-)

$a - $b

Multiplication(*)

$a * $b

Division(/)

$a / $b

Modulus(%)

$a % $b

String Operator

Use "." to concatenate 2 strings

Example:

$a = "Hello ";

$b = $a . "World!"; // now $b = "Hello World!"

          

Boolean operators

Example

Operator

Result

$a and $b

And

Both $a,$b are True, return True

$a or $b

Or

Either $a or $b is True, return True

$a xor $b

Or

Only one of $a,$b is True ¡A return True, Otherwise return False

!$a

Not

$a is not True, return True

$a && $b

And

Both $a, $b are True,return True

$a || $b

Or

One of $a, $b is True, return True

Comparison Operators

Example

Operator

result

$a == $b

equal to (==)

$a equals to $b, return True

$a != $b

not equal to (!=)

$a is not equal to $b, returnTrue

$a < $b

Less than (<)

$a is less than $b, return True

$a > $b

greater than (>)

$a is greater than $b, return True

$a <= $b

less than or equal (<=)

$a is less than or equal to$b, returnTrue

$a >= $b

greater than or equal (>=)

$a is greater than or equal to $b, return True

PHP+DBMaker

The procedures

To write a program to access a database, the first thing you need to do is to connect to the database, then execute SQL statements. There are 2 ways to do it. One is to prepare the SQL statement and then repeat the execution of the SQL. The other is only by EXEC(PREPARE+EXECUTE) in which it always prepares then executes every time. Therefore, if an particular SQL statement will be executed frequently, then the first way is recommended. That is, prepare first, then repeat the execution of the SQL statement to improve the performance. After executing an SQL statement, a RESULT SET will exist and you can use a variable to get the result set back. And then you can show the result by using ODBC_RESULT,ODBC_FETCH_ROW,ODBC_FETCH_INTO...etc

Notice: Remember to put the Dmconfig.ini file into the directory ~dbmaker/data

Connecting to a database

ODBC_CONNECT

Syntax:

int odbc_connect(string dsn, string user, string password);

Description:

it will return a connect id(integer) if successful, otherwise it returns 0

ODBC_CLOSE

Syntax:

void odbc_close(int connection_id);

Description:

It will fail if a transaction is still running.

ODBC_CLOSEALL

Syntax:

void odbc_close_all(void);

Description:

It will fail if a transaction is still running.

Example:


<HTML>

<TITLE>

<HEAD>ODBC_CLOSE_ALL</HEAD>

</TITLE>

<body>

<?

  $Cn=ODBC_connect("PHP3TEST","SYSADM","");

  $Cn1=ODBC_connect("EXDM30","SYSADM","");

  echo "Connected Cn and Cn1<P>";

  odbc_close_all();

  echo "CLOSE ALL<p>";

  $Rs=ODBC_EXEC($Cn,"Select * from TestSample");

  $Rs1=ODBC_EXEC($Cn1,"Select * from Card");

  if($Rs){

    echo "Cn Connection not Close<P>";

  }

  else

  {

    echo "Cn Connection Close<P>";

  }

  if($Rs1)

  {

    echo "Cn1 Connection not Close<P>";

  }

  else

  {

    echo "Cn1 Connection Close<P>";

  }

  echo $HOME;

?>

</body>

</HTML>
Transaction control

ODBC_AUTOCOMMIT

Syntax:

int odbc_autocommit(int connection_id, int [OnOff])

Description:

Set the default so the transaction is automatically committed for the specified connection id. When the onoff is true, autocommit is the default.

ODBC_COMMIT

Syntax :

int odbc_commit(int connection_id)

Description:

commit the transaction for the specified connection. Return True if successful, otherwise return False.

ODBC_ROLLBACK

Syntax:

int odbc_rollback(int connection_id)

Description:

Rollback the transaction for the specified connection. Return True if successful, otherwise return False.

Example:


<HTML>

<HEAD>

<TITLE><h1>Test AutoCommit Execute Time <h1></TITLE>

</HEAD>

<BODY>

<?

  $conn=ODBC_CONNECT("PHP3TEST","SYSADM","");

  if ($conn){

    if(ODBC_EXEC($conn,"Create table T1(c1 int,c2 char(10))")) {

      ODBC_AUTOCOMMIT($conn,1);

      //do some insert 

      ODBC_AUTOCOMMIT($conn,0);

      //do some insert

    }

    ODBC_EXEC($conn,"Drop table T1"); 

    ODBC_COMMIT($conn);

  }

  ODBC_CLOSE($conn);

?>

</BODY>

</HTML>

          
Execute SQL statements

ODBC_PREPARE

Syntax:

int odbc_prepare(int connection_id, string query_string)

Description:

Prepare an SQL statement for the next execution. Return a result identifier id if successful, which is for execution in the ODBC_EXECUTE command.

ODBC_EXECUTE

Syntax:

int odbc_execute(int result_id, array [parameters_array])

Description:

Execute a prepared SQL statement. Return True if successful, otherwise return False. If there is any parameter required by the prepared SQL statement, use array[parameters_array].

ODBC_EXEC

Syntax:

int odbc_exec(int connection_id, string query_string)

Description:

PREPARE and execute the specified SQL statement, which is equivalent to using theODBC_PREPARE and ODBC_EXECUTE commands. Return True if successful, otherwise return False.

ODBC_DO

Syntax:

string odbc_do(int conn_id, string query)

Description:

Same asODBC_EXEC.

Example:


<HTML>

<HEAD>

</HEAD>

<BODY>

<?

$conn=ODBC_connect("PHP3TEST","SYSADM","");

if($conn)

{

  $res=odbc_prepare($conn,

                    "insert into TestODBC

                       values(?,?,?)");

  $param[0]=3;

  $param[1]="test";

  $param[2]="insert";

  odbc_execute($res,$param);

  odbc_free_result($res);

  $res=odbc_EXEC($conn,"select * from TestODBC");

  echo "insert a row (1,test,insert) into table";

  echo odbc_result_all($res);

  odbc_free_result($res);

  odbc_close($conn);

}

?>

</BODY>

</HTML>

          
Extracting data

ODBC_CURSOR

Syntax:

string odbc_cursor(int result_id);

Description:

Get a CURSORNAME. Return a CURSOR NAME for the specified result id if successful.

Example:


<HTML>

<HEAD>

<TITLE>ODBC FUNCTION TEST</TITLE>

</HEAD>

<BODY>

<h5>Test Cursor of deleting odd records and update

even records c2char to 'handy'</h5>

<?

$conn=odbc_connect("PHP3TEST","SYSADM","");

if($conn)

{ 

  Error_Reporting(0);

  odbc_exec($conn,"drop table PHP3CURSOR");

  odbc_exec($conn,"Create table PHP3CURSOR(c1Int int ,c2Char char(10))");

  for($i=0;$i < 50;$i++)

  {

    $resexec=odbc_exec($conn,"insert into PHP3CURSOR values($i,'Test')");

    ODBC_COMMIT($conn);

    odbc_free_result($resexec); 

  } 

  $res=odbc_exec($conn,"select * from PHP3CURSOR");

  echo odbc_result_all($res),"rows";

  odbc_free_result($res); 

  $res=odbc_exec($conn,"select * from PHP3CURSOR for update of c2Char");

  $Cursor=odbc_cursor($res);

  $CurUpdate=odbc_prepare($conn,"update PHP3CURSOR set c2Char=?

                                   where current of $Cursor");

  $CurDelete=odbc_prepare($conn,"Delete from PHP3CURSOR

                                   where current of $Cursor");

  if($CurUpdate and $CurDelete)

  { 

    while(odbc_fetch_row($res))

    {

      if(odbc_result($res,1)%2==0) 

      {

        $str=chop(odbc_result($res,2)) . "*";

        $param[0]=$str;

        odbc_execute($CurUpdate,$param);

      }

      else

      {

        odbc_execute($CurDelete);

      }

      odbc_commit($conn);

    }

  } 

  odbc_free_result($res);

  $res=odbc_exec($conn,"select * from PHP3CURSOR");

  echo odbc_result_all($res),"rows";

  odbc_free_result($res);

  odbc_close($conn);

} 

?>

</BODY>

</HTML>

          

ODBC_RESULT_ALL

Syntax:

int odbc_result_all(int result_id, string [format])

Description:

Display the RESULT SET in HTML format. odbc_result_all will print out all data for the result id returned by ODBC_EXEC.

Example:


<HTML>

<HEAD>

<TITLE><H1>TEST ODBC FUNCTION</H1></TITLE>

</HEAD>

<BODY>

<?

$CONN=ODBC_CONNECT("PHP3TEST","SYSADM","");

IF($CONN)

{

  $RES=ODBC_EXEC($CONN,"SELECT * FROM TestODBC");

  $STRRS=ODBC_RESULT_ALL($RES);

  ECHO $STRRS;

  ECHO "|a¡MeRA";

}

?>

</BODY>

</HTML>

          

ODBC_FETCH_INTO

Syntax:

int odbc_fetch_into(int result_id, int [rownumber], array result_array)

Description:

FETCH a record to an array. Return the position of the record in the result set if successful, otherwise return False. The array for getting data back must be in PASSING BY REFERENCE, and the index of the array starts from 0.

Example:


<HTML>

<TITLE>

  <HEAD>ODBC_fetch_into,ODBC_fetch_row</HEAD>

</TITLE>

<body>

<?

  $Cn=ODBC_connect("PHP3TEST","SYSADM","");

  if($Cn)

  {

    $Rs=odbc_exec($Cn,"select * from TestODBC");

    $Colnum=odbc_num_fields($Rs); 

    while(odbc_fetch_into($Rs,&$Str))

    { 

      for($i=0;$i<3;$i++) 

      {

        echo $Str[$i] , "===== ";

      }

      echo "<P>";

    }

  }

?>

</body>

</HTML>

ODBC_FETCH_ROW

Syntax:

int odbc_fetch_row(int result_id, int [row_number])

Description:

FETCH a record each time. ODBC_FETCH_ROW can be used for the result set produced by ODBC_DO or ODBC_EXEC. ODBC_FETCH_ROW will fetch the next record if the row_number is not specified.

ODBC_RESULT

Syntax:

string odbc_result(int result_id, mixed field)

Description:

Get a certain column of a record and the mixed filed could be a column or column number which starts from 1.

ODBC_RUM_ROWS

Syntax:

int odbc_num_rows(int result_id);

Description:

Get the number of records in the RESULT SET. If the SQL statement is insert, update, or delete, then return the number of records effected. Most databases could not use ODBC_RUM_ROWS to get the number of records after a select statement.

ODBC_NUM_FIELDS

Syntax:

int odbc_num_fields(int result_id)

Description:

Get the number of columns in the RESULT SET.

ODBC_FIELD_NUM

Syntax:

int odbc_fieldnum(int result_id, string field_name)

Description:

Return the order number of the specified column in the RESULT SET.

ODBC_FIELD_NAME

Syntax:

string odbc_fieldname(int result_id, int field_number)

Description:

Return the column name of the order number specified by field_number in the RESULT SET.

ODBC_FIELD_TYPE

Syntax:

string odbc_field_type(int result_id, mixed field)

Description:

Return the data type of the specfied column in the RESULT SET.

ODBC_FREE_RESULT

Syntax:

int odbc_free_result(int result_id)

Description:

Close the RESULT SET