Sunday, September 23, 2007

php interview questions and answers

How are database errors handled in PHP?

When using the OCI extension Module, the OCIError() function can be used to obtain an array with error code, message, offset and SQL text. One can also obtain the error for a specific session or cursor by supplying the appropriate handle as an argument to OCIError(). Without any arguments, OCIError() will return the last encountered error.




$err = OCIError();

var_dump($err);



print "\nError code = " . $err[code];

print "\nError message = " . $err[message];

print "\nError position = " . $err[offset];

print "\nSQL Statement = " . $err[sqltext];

?>



When using the ORA Extension Module, one can use the ora_error() and ora_errorcode() functions to report errors:




print "\nError code = " . ora_errorcode();

print "\nError message = " . ora_error();

?>





How does one call stored procedures from PHP?

The following example creates a procedure with IN and OUT parameters. The procedure is then executed and the results printed out.




// Connect to database...

$c=OCILogon("scott", "tiger", "orcl");

if ( ! $c ) {

echo "Unable to connect: " . var_dump( OCIError() );

die();

}



// Create database procedure...

$s = OCIParse($c, "create procedure proc1(p1 IN number, p2 OUT number) as " .

"begin" .

" p2 := p1 + 10;" .

"end;");

OCIExecute($s, OCI_DEFAULT);



// Call database procedure...

$in_var = 10;

$s = OCIParse($c, "begin proc1(:bind1, :bind2); end;");

OCIBindByName($s, ":bind1", $in_var);

OCIBindByName($s, ":bind2", $out_var, 32); // 32 is the return length

OCIExecute($s, OCI_DEFAULT);

echo "Procedure returned value: " . $out_var;



// Logoff from Oracle...

OCILogoff($c);

?>





Does PHP offer Oracle connection pooling?

Unfortunately PHP does not offer connection pooling. One can open "persistent" Oracle connections with the ora_plogon() and OCIPLogon() function calls. Nevertheless, persistent connections do not scale as well as connection pooling. A persistent connection will be kept open for a process, but it will not allow connections to be shared between different processes.



Third party tools like SQL Relay (http://sqlrelay.sourceforge.net/) can be used to enable connection pooling for Oracle and other databases.

No comments: