Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Chapter 4 Files & Database Handling

Uploaded by

omkar2342004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 4 Files & Database Handling

Uploaded by

omkar2342004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter 4 File and database

handling :
Databases (PHP- PostgreSQL)
Working with Files
 A file is nothing more than an ordered sequence of bytes stored
on hard disk, floppy disk, CD-ROM, or other storage media.
 PHP provides two sets of file-related functions, distinguished by
the ways in which they handle files: some use a file handle, or a
file pointer; others use filename strings directly.
 A file handle is simply an integer value that is used to identify
the file you want to work with until it is closed. If more than one
file is opened, each file is identified by its own uniquely assigned
handle.
 A file handle is contained in a variable (named like any other
PHP variable, and in examples typically $fp, for file handle). The
integer value the file handle variable contains/ identifies the
connection to the file you are working with.

PROF. SHITAL PASHANKAR


Operations on file

fopen():
 Opening and closing a file This is used to open a file
,returning a file handle associated with opened file .It can
take three arguments :fname, mode and optional
use_include_path.
Ex:-$fp=fopen(“data.txt”,"r");
 List of modes used in fopen are:

PROF. SHITAL PASHANKAR


Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a
new file if it doesn't exist. File pointer starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File
pointer starts at the end of the file. Creates a new file if the file doesn't
exist
r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a
new file if it doesn't exist. File pointer starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved. File
pointer starts at the end of the file. Creates a new file if the file doesn't
exist

PROF. SHITAL PASHANKAR


Operations on file

 fclose():
 This is used to close file, using its associated file handle as
a single argument
 Ex:- fclose($fp);

PROF. SHITAL PASHANKAR


Reading and Writing to Files
 fread( ):
This function is used to extract a character string from a file
and takes two arguments, a file handle and a integer length.
Ex: fread($fp,10);

 fwrite():
This function is used to write data to a file and takes two
arguments, a file handle and a string.
Ex: fwrite($fp,”HELLO”);

PROF. SHITAL PASHANKAR


Write a php program to read a line
from a file.
/* File1.txt
Welcome to file handling using php… */
<?php
$fileName = "File1.txt";
$fp = fopen($fileName,"r"); // or die("Error in opening file" );
if( $fp == false ) {
echo ( "Error in opening file" );
exit();
}
$fileData = fread( $fp, 80 );
echo $fileData;
fclose($fp);
?>
PROF. SHITAL PASHANKAR
Write a php program to write a line in
a file.
<?php
$fileName = "File1.txt";
$fp = fopen($fileName,"w"); //or die("Error
in opening file");
fwrite( $fp, "This is a sample text to write….\n" );
fclose($fp);
?>

PROF. SHITAL PASHANKAR


Reading and Writing Characters in Files

 fgetc():
Function can be used to read one character from file at a file. It
takes a single argument ,a file handle and return just one character
from the file .It returns false when it reached to end of file.
$one_char = fgetc($fp)
 fgets():
This function is used to read set of characters it takes two arguments,
file pointer and length. It will stop reading for any one of three
reasons:
The specified number of bytes has been read A new line is
encountered The end of file is reached.
 fputs():
This is simply an alias for fwrite() .

PROF. SHITAL PASHANKAR


Reading Entire Files
 file():
This function will return entire contents of file.This function will
automatically opens,reads,anclose the file.It has one argument :a
string containing the name of the file.It can also fetch files on remote
host.
Array file("myfile.txt")
 fpassthru():
This function reads and print the entire file to the web browser. This
function takes one argument ,file handle.If you read a couple of lines
from a file before calling fpassthru() ,then this function only print the
subsequent contents of a file.

 readfile():
This function prints content of file without having a call to fopen() It
takes a filename as its argument ,reads a file and then write it to
standard output returning the number of bytesread(or false upon
error).

PROF. SHITAL PASHANKAR


Examples

<?php <?php
$fp = fopen("test_file.txt","r"); echo readfile("test_file.txt");
echo fpassthru($fp); ?>
fclose($fp);
?>

PROF. SHITAL PASHANKAR


Random Access to File Data

What you really need is some way to move the file


position indicator around in the file without having to
close and reopen the file.
fseek()
Specifying a file handle (such as $fp) and an integer
offset (5 in the following example) as arguments, fseek()
will move the file position indicator associated with fp to
a position determined by offset.
Fseek(filepointer, offset[, whence]);

PROF. SHITAL PASHANKAR


Random Access to File Data

By default, the offset is measured in bytes from the


beginning of the file. Here's an example:
fseek($fp, 5);
 $one_char = fgetc($fp);
 This code places the file's file position indicator associated with
handle $fp just after the fifth byte in that file. The call to fgetc()
therefore returns the contents of the sixth byte.
 A third optional argument (called whence in the documentation)
can be specified with any of the following values to calculate the
relative offset:
SEEK_SET: The beginning of the file + offset.
SEEK_CUR: Current position + offset (default).
SEEK_END: End of the file + offset.

PROF. SHITAL PASHANKAR


Random Access to File Data

ftell()
The ftell() function takes a file handle and returns the
current offset (in bytes) of the corresponding file position
indicator. For example:
$fpi_offset = ftell($fp);
rewind(); //same as fseek($fp,
0);

Rewind()
This is similar to the rewind button on your cassette
player?it takes a file handle and resets the
corresponding file position indicator to the beginning of
the file.
PROF. SHITAL PASHANKAR
Getting Information on Files

you can use file_exists() to discover


whether the file exists.
Boolean file_exists(filename);
Example : $ans=file_exists("count.dat");

Filesize()
This returns the size of the specified file in
bytes, or False upon error.
$size=filesize("count.dat");

PROF. SHITAL PASHANKAR


Getting Information on Files

Time-Related Properties

Files have other properties that can provide useful


information. These will principally depend on the
operating system in which they are created and
modified.
On UNIX platforms such as Linux, for example,
properties include creation date, modification
date, last access date, and user permissions.
The function fileatime() returns the last access
time for a file in a UNIX timestamp format.(A UNIX
timestamp is a long integer value).
PROF. SHITAL PASHANKAR
Time-Related Properties

filectime() returns the time at which the file was last


changed as a UNIX timestamp. A file is considered
changed if it is created or written, or when its
permissions have been changed.
filemtime() returns the time at which the file was
last modified as a UNIX timestamp. The file is
considered modified if it is created or has its
contents changed.
The getdate() function is also very useful when
working with timestamps. It returns an associative
array containing the date information present in a
timestamp. The array includes such values as the
year, the month, the day of the month etc.
PROF. SHITAL PASHANKAR
<?php
if(file_exists("file1.txt")) OUTPUT :
{
echo "\nFile size : File size : 50
Last access time is :1604642460
".filesize("file1.txt"); Array
(
echo"\n Last access time is [seconds] => 0
:".fileatime("file1.txt")."\n"; [minutes] => 31
[hours] => 11
print_r(getdate(filectime(" [mday] => 6
file1.txt"))); [wday] => 5
[mon] => 11
echo"\nLast access : [year] => 2020
".date("F d Y [yday] => 310
[weekday] => Friday
H:i:s.",filemtime("file1.txt")); [month] => November
} )
[0] => 1604642460

else
Last access : November 06 2020 11:31:00.
echo"File does not exists";
?>

PROF. SHITAL PASHANKAR


Ownership and Permissions

 You also can get information on file ownership and permissions.


 On a UNIX system like Linux, all files are associated with a specific user
and a specific group of users, and assigned flags that determine
who has permission to read, write, or execute their contents.
 User groups are defined in UNIX so that permissions can be easily
extended to a certain set of users without extending them to
everyone on the system. For example, several users who are working
on the same project might want to share files with each other, but
with no one else.
 Each of these three permissions (read, write, and execute) can be
granted to (or withheld from):
The file owner: By default, the user whose account was used to
create the file.
A group of users: By default, the group to which the owner
belongs.
All users: Everyone with an account on the system

PROF. SHITAL PASHANKAR


 Users and groups in UNIX are identified by ID numbers as well as names. If
you want to get information on a user by his ID number, you can use the
posix_getpwuid() function, which returns an associative array with the
following references:

Name Description

name The shell account username of the user

passwd The encrypted user password

uid The ID number of the user

gid The group ID of the user

gecos A Comma-separated list containing the user's full name,


office phone, office number, and home phone number.
On most systems, only the user's full name is available
Dir The absolute path to the home directory of the user

shell Absolute path to the user's default shell

PROF. SHITAL PASHANKAR


 posix_getgrgid(), returns an associative array on a group identified
by a group ID. It contains the following elements of the group
structure:

Name Description

name The name of the group

Gid The ID number of the group

Members The number of members belonging to the


group

PROF. SHITAL PASHANKAR


You can use the following three functions to get at
this information from your PHP scripts. Each takes a
single argument, a filename string.
fileowner(): Returns the user ID of the owner of the
specified file.
filegroup(): Returns the group ID of the owner of the
specified file.
filetype(): Returns the type (fifo, char, dir, block, link,
file, or unknown) of the specified file.
is_file() returns True if the given filename refers to a
regular file.

PROF. SHITAL PASHANKAR


Copying, Renaming, and Deleting Files

The copy() function takes two string arguments referring


to the source and destination files, respectively. The
following function call copies the source file copyme.txt
to the destination file copied.txt.:
 if(!copy("./copyme.txt", "copied.txt")) die("Can't copy the file
copyme.txt to copied.txt!");
The rename() function is used to rename a file as follows:
if(!rename ("./address.dat", "address.backup")) die("Can't rename the
file address.dat to address.backup!");
The unlink() function takes a single string argument
referring to the name of a file you want to delete.
if(!unlink("./trash.txt")) die ("Can't delete the file trash.txt!");

PROF. SHITAL PASHANKAR


Write a PHP program to count number of lines, words and characters from a file.

<?php
$file = "test_file1.txt";
// read file contents into string
$str = file_get_contents($file) or die("Can not read from file");
echo $str ."<br>";
$array = file($file) or die("Can not read from file");
echo "Counted " . count($array) ." line(s). <br>";
$nchar = strlen($str);
echo "Counted " .$nchar. " character(s) with space.<br>";
$cwords = str_word_count($str);
echo "Counted " . $cwords . " word(s).<br>";
$new = preg_replace('/\s+/','', $str);//for removing space
from $str
$nchar = strlen($new);
echo "Counted " .$nchar. " character(s) without space.<br>";
?>

PROF. SHITAL PASHANKAR


Using PHP to access
a database
• There are two ways to access database from PHP:
• Database – specific extension
• Your code is intimately tied to the database
you’re using
• Database – independent PEAR DB library
• Moving between databases systems is as simple
as changing one line of your program.
• PEAR is short for "PHP Extension and
Application Repository"

Prof. Shital Pashankar


Data Manipulation
Language (DML):
• Used to retrieve and
modify data in an existing
Relational database – SELECT, INSERT,
Databases UPDATE and DELETE

and SQL Data Definition


Language (DDL):
• Used to create and modify
the database structures –
CREATE, ALTER and DROP.

Prof. Shital Pashankar


• Creating a Database:
• $ create database test
Data This should produce as response:
CREATE DATABASE
Definition • $ drop database test
• If you do not want to use your
Language database anymore you can
remove it
• $ psql test
(DDL): • which allows you to interactively
enter, edit, and
execute SQL commands

Prof. Shital Pashankar


• CREATE TABLE cities ( name varchar(80),
location point );
• DROP TABLE tablename ;

Prof. Shital Pashankar


• create table movie(mno int primary key, mname varchar(20), rel_year int);

• INSERT INTO movie VALUES(101,'DDLG',1992);

• DELETE FROM movie WHERE rel_year=1979;

• UPDATE movie SET rel_year=1988 WHERE mname=‘Ghar‘;

• SELECT * FROM movie;

• SELECT mname FROM movie,mov_act,actor WHERE


movie.mno=mov_act.mno AND actor.ano=mov_act.ano AND aname='ABC';

Prof. Shital Pashankar


PostgreSQL and PHP:
connecting to database
resource pg_connect(string $connection_string[,int
$connect_type])

• The pg_connect function will create a new


connection for each instance of the function.
<?php
$conn_string=“host=localhost port=5432
dbname=test user=postgres password=postgres”;
$dbcon=pg_connect($conn_string);
?>

Prof. Shital Pashankar


resultset pg_query($dbcon, $query);

• To execute SQL query use pg_query()


function which accept SQL query string
Executing as parameter and returns result or error
otherwise
SQL • Retrieving data after executing SELECT
query:
query • 1) pg_fetch_row()
• 2) pg_fetch_assoc()
• 3) pg_fetch_object()

Prof. Shital Pashankar


Retrieving data after executing
SELECT query

1) pg_fetch_row(): returns a row as an indexed array of


string values otherwise false.

2) pg_fetch_assoc(): returns a row as an associative


array otherwise false. The keys of the associative array
are the column names.

3) pg_fetch_object(): returns an object with properties


that correspond to the fetched row’s field names.

Prof. Shital Pashankar


Closing the connection

pg_close($dbcon);

Prof. Shital Pashankar


postgres=# create database test;
WARNING: could not flush dirty data: Function not implemented
CREATE DATABASE

postgres=# \c test;
You are now connected to database "test" as user "postgres".

test=# create table teacher(tno int primary key, tname varchar(20));


CREATE TABLE

test=# insert into teacher values(1,'Shital'),(2,'Awantika'),(3,'Sarika'),(4,'Sarita');


INSERT 0 4

test=# select * from teacher;


tno | tname
-----+----------
1 | Shital
2 | Awantika
3 | Varsha
4 | Sarita
(4 rows)
Prof. Shital Pashankar
Example
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=test";
$credentials = "user=postgres password=postgres";
$dbcon = pg_connect(" $host $port $dbname $credentials")
or die(“Could not connect to server…”);
$resultset = pg_query($dbcon, "select * from teacher") or
die(“SELECT query failed…”);
echo"<table
border=1><tr><th>tno</th><th>tname</th></tr>";
while ($row = pg_fetch_row($resultset)) {
echo "<tr><td> $row[0] </td><td> $row[1]
</td></tr>"; }
echo "</table>";
pg_free_result($resultset);
pg_close($dbcon); ?>

Prof. Shital Pashankar


Write a PHP program to create a table movie(mno, mname,
rel_year) using database connection.
<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=test";
$login = "user=postgres password=postgres";

$dbcon = pg_connect(" $host $port $dbname $login") or die(“Could not


connect to server…”);

$resultset = pg_query($dbcon, "create table movie(mno int primary key, mname


varchar(20), rel_year int); ") or die(“Create query failed…”);

echo "table created successfully";


pg_free_result($resultset);
pg_close($dbcon);
?>
Prof. Shital Pashankar
Write a PHP program to insert a record in movie(mno, mname, rel_year)
table using database connection and display its data in tabular format.

<?php
$host = "host=127.0.0.1";
$port = "port=5432";
$dbname = "dbname=trial";
$login = "user=postgres password=postgres";
$dbcon = pg_connect(" $host $port $dbname $login") or die(“Could
not connect to server…\n”);
$resultset = pg_query($dbcon, "INSERT INTO movie VALUES(101,'DDLG',1992);
") or die(“Insert query failed…\n”);
$resultset = pg_query($dbcon, "select * from movie") or die(“SELECT
query failed…\n”);
echo"<table border=1><tr><th>Mno</th><th>Mname</th>
<th>Rel_Year</th> </tr>";
while ($row = pg_fetch_row($resultset)) {
echo "<tr><td> $row[0] </td><td> $row[1] </td><td> $row[2] </td></tr>";
}
echo "</table>"; pg_free_result($resultset);
pg_close($dbcon); ?> Prof. Shital Pashankar
Consider the following entities and their relationships
Doctor (doc_no, doc_name, address, city, area)
Hospital (hosp_no, hosp_name, hosp_city) Doctor and
Hospital are related with many-many relationship.
Create a RDB in 3 NF for the above and solve following
Using above database, write a PHP script which
accepts hospital name and print information about
doctors visiting / working in that hospital in tabular
format.

Prof. Shital Pashankar


<?php
$hname=$_GET['hname'];
$con_string = "host=127.0.0.1 dbname=trial1 port=5432 user=postgres
password=postgres";

$con = pg_connect($con_string)or die("Cannot connect...");

$q="select doctor.dno,dname,city,status from doctor,hospital,doho where


doctor.dno=doho.dno and hospital.hno=doho.hno and
hospital.hname='$hname'";
$resultset = pg_query($con,$q) or die("SELECT query ERROR.......");
echo"<table border=2 height=50 width=50>";
if(pg_num_rows($resultset)>0)
{
echo"<tr><th>Doc no</th><th>Doc
name</th><th>Address</th><th>Status</th></tr>";
while($row=pg_fetch_row($resultset)){
echo"<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td
></tr>";
}
}
echo"</table>";
pg_close($con);
?> Prof. Shital Pashankar
pg_prepare()

 Syntax:
Resource
pg_prepare([resourse
$connection],string
$stmtname,string $query)
 This submits a request to create a
prepared statement with the given
parameters and waits for
completion.
$result=pg_prepare($con,”my_quer
y”,”select * from movie”);

Prof. Shital Pashankar


pg_execute()
 Syntax:
resource pg_execute ([ resource $connection ],
string $stmtname, array $params )
 This routine sends a request to execute a prepared
statement with given parameters and waits for the result.
$result=pg_execute($con,”my_query”,array());

Prof. Shital Pashankar


<?php
$con_string = "host=127.0.0.1 port=5432 dbname=trial1 user=postgres
password=postgres";

$con = pg_connect($con_string)or die("Cannot connect...");

$rs=pg_prepare($con,"my_query","select * from movie where rel_year=$1 ");


//$1 is act like placeholder which value will be substituted using pg_execute()
third para. value.

$rs=pg_execute($con,"my_query",array(2018));

echo"<table border=1><tr><th>Movie No</th><th>Movie


Name</th><th>Release Year</th></tr>";
while($row = pg_fetch_row($rs))
echo "<tr><td>$row[0]</td><td> $row[1]</td><td> $row[2]</td></tr>";

echo"</table>";
pg_close($con);
?>

Prof. Shital Pashankar


PEAR DB
• PEAR DB library is used to connect to a
database ,issue queries, check for errors and
transform the result of query into HTML.
• Steps for connecting database to PHP using
PEAR DB:
1. DSN
2. Connecting
3. Error checking
4. Issuing query
5. Fetching result from query
6. Disconnecting

Prof. Shital Pashankar


1) Data Source Name (DSN)
• It specifies where db is located, the type of database, the
username and password , the protocol and host specification
and name of the database. All these parameters are embedded
in a string.
• Syntax:
• Type(dbsyntax)://username:password @ protocol +
hostspecification/database
• Example:
• $dsn = pgsql://postgres:postgres@localhost/Indira

Prof. Shital Pashankar


Name Database
Mysql MySQL
Pgsql PostgreSQL
Ibase InterBase
Data Msql Mini SQL
Source Mssql Microsoft SQL Server
Names oci8 Oracle 7/8/8i
Odbc ODBC
Sybase SyBase
Ifx Informix

Fbsql FrontBase

Prof. Shital Pashankar


2) Connecting

• Once the DSN is made, a connection must be created to the


database using the connect method. Which returns a database
object that can be used for issuing queries etc.
• Syntax:
• DB :: connect(DSN, [options]);
• Options: persistent, optimum, debug.
• Example:
• $db = DB :: connect($dsn);

Prof. Shital Pashankar


• PEAR DB methods returns error message
if an error occurs. Which can be checked
using database isError() method
• Syntax:
• DB :: isError()
3) Error • Example:

Checking • $db = DB :: connect($dsn);


• if(DB :: isError($db))
• die($db → getMessage());
• The method returns true if an error
occurs and displays the error message
reported by getMessage() function.

Prof. Shital Pashankar


4) Issuing
the Query

Prof. Shital Pashankar


5) Fetching Results From Query

• The fetchRow() method on a query returns an array of data, NULL if there


is no more data or DB_ERROR if an error occured.
• Syntax:
$row = $result → fetchRow([mode]);
• Mode values : DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC,
DB_FETCHMODE_OBJECT
• Example:
while($row = $result → fetchRow()){
if(DB :: isError($row)) {
die($row → getMessage()); }
echo”$row[0]”; }

Prof. Shital Pashankar


5) Fetching Results From Query
(Continued...)

• The fetchInto() method not only gets the next row, but also stores it
into the array variable passed as parameter.
• Syntax:
• $success = $result → fetchInto(array,[mode] );
• Example:
• while($success = $result → fetchInto($row)){
• if(DB :: isError($success)) {
• die($success → getMessage()); }
• echo”$row[0]”;
• }

Prof. Shital Pashankar


5) Fetching Results From Query
(Continued...)

• A queryresult object typically holds all the rows returned by


the query. This may consume a lot of memory. To return the
memory consumed by the result of a query to the OS, use the
free() method.
• Syntax:
• $result → free( );

Prof. Shital Pashankar


6)Disconnecting

• To force PHP to disconnect from the database, use the disconnect() method
on the database object
• Syntax:
$db → diconnect( );

Prof. Shital Pashankar


PEAR DB Basic Program
<?php
include "DB.php";
$dsn = "pgsql://postgres:postgres@localhost/trial1";
//DB::connect("mysql://db_username:db_password@db_host/db_database");
$db = DB::connect($dsn);
if(DB::isError($db)) {
die($db->getMessage());
}
$sql = "select * from teacher where tid=1";
$result = $db->query($sql);
while($row = $result->fetchRow()) {
echo "\n$row[0] $row[1] $row[2] $row[3]\n";
}
$result->free();
$db->disconnect();
?>
Prof. Shital Pashankar
Advanced Database Techniques :
1)Placeholders

Just as printf() builds a string by inserting values into a template, the PEAR DB can
build a query by inserting values into a template.

Pass the query() function SQL with ? In place of specific values and add a second
parameter consisting of the array of values to insert into the SQL.

$result = $db → query(SQL, values);


Prof. Shital Pashankar
Advanced Database Techniques :
1)Placeholders
• Example:
$books = array(array('FOUNDATION', 1951),array('SECOND FOUNDATION',1953),
array('FOUNDATION AND EMPIRE', 1952));
foreach($books as $book){
$db → query('insert into books(title,pub_year) values(?,?)', $book);
}
• There are three characters that you can use as a placeholder values in an SQL
query:
? : A string or number, which will be quoted if necessary(recommended).
| : A string or number, which will never be quoted.
& : A filename, the contents of which will be included in the
statement.(e.g. for storing an image file in a BLOB field).

Prof. Shital Pashankar


Advanced Database Techniques :
2)Prepare / Execute
• When issuing the same query repeatedly, it can be more efficient to compile the query once
and then execute it multiple times using the prepare(), execute() and executeMultiple() methods.
• The first step is to call prepare() on the query:
• $compiled = $db → prepared(SQL);
• It returns a compiled query object.
• The execute() method fills in any placeholders in the query and sends it to the RDBMS:
• $response = $db → execute(compiled, Values);
• Values are array contains the values for the placeholders in the query.
• The return value is either a query response object, or DB_ERROR if an error occurred.
• Example:
$books = array(array('FOUNDATION', 1951),array('SECOND FOUNDATION',1953),
array('FOUNDATION AND EMPIRE', 1952));
$compiled = $q → prepare('insert into books(title,pub_year) values(?,?)');
foreach($books as $book){
$db → execute($compiled, $book);
}
Prof. Shital Pashankar
Advanced Database Techniques :
2)Prepare / Execute ( continued).....
• The executeMultiple() method takes a two-dimensional array of values to insert:
• $responses = $db → executeMultiple(complied, Values);
• The values array must be numerically indexed from 0 and have values that are arrays of values
to insert.
• The compiled query is executed once for every entry in Values, and the query responses are
collected in $responses.
• Example:
• $books = array(array('FOUNDATION', 1951),array('SECOND FOUNDATION',1953),
array('FOUNDATION AND EMPIRE', 1952));
• $compiled = $q → prepare('insert into books(title,pub_year) values(?,?)');
• $db → executeMultiple($compiled, $books);

Prof. Shital Pashankar


Advanced Database Techniques :
3)Shortcuts

• PEAR DB provides number of methods that perform a query and fetch


the results in one step: getOne(), getRow(), getCol() and getAll(). All these
methods permit placeholders.

• The getOne() method fetches the first column of the first row of data
returned by an SQL query:
• $value = $db → getOne(SQL, [,values]);

• The getRow() method returns the first row of data returned by an SQL
query:
• $row = $db → getRow(SQL, [,values]);

Prof. Shital Pashankar


Advanced Database Techniques :
3)Shortcuts (continued...)

• The getCol() method returns a single column from the data returned by
an SQL query:
• $col = $db → getCol(SQL, [, column [,values]]);
• The column parameter can be either a number(0, default is first
column), or the column name.

• The getAll( ) method returns an array of all the rows returned by the
query:
• $all = $db->getAll(SQL [, values [, fetchmode ]]);

• All the get*( ) methods return DB_ERROR when an error occurs.

Prof. Shital Pashankar


Details about a Query Response

• Four PEAR DB methods provide you with information on a query result object: numRows( ) ,
numCols( ), affectedRows( ), and tableInfo( ).

• The numRows( ) and numCols( ) methods tell you the number of rows and columns returned
from a SELECT query:
• $howmany = $response->numRows( );
• $howmany = $response->numCols( );

• The affectedRows( ) method tells you the number of rows affected by an INSERT, DELETE, or
UPDATE operation:
• $howmany = $response->affectedRows( );

• The tableInfo( ) method returns detailed information on the type and flags of fields returned
from a SELECT operation:
• $Assoc_info = $response->tableInfo( );
Prof. Shital Pashankar

You might also like