Chapter 4 Files & Database Handling
Chapter 4 Files & Database Handling
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.
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:
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
fclose():
This is used to close file, using its associated file handle as
a single argument
Ex:- fclose($fp);
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”);
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() .
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).
<?php <?php
$fp = fopen("test_file.txt","r"); echo readfile("test_file.txt");
echo fpassthru($fp); ?>
fclose($fp);
?>
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
Filesize()
This returns the size of the specified file in
bytes, or False upon error.
$size=filesize("count.dat");
Time-Related Properties
else
Last access : November 06 2020 11:31:00.
echo"File does not exists";
?>
Name Description
Name Description
<?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>";
?>
pg_close($dbcon);
postgres=# \c test;
You are now connected to database "test" as user "postgres".
<?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.
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”);
$rs=pg_execute($con,"my_query",array(2018));
echo"</table>";
pg_close($con);
?>
Fbsql FrontBase
• 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]”;
• }
• To force PHP to disconnect from the database, use the disconnect() method
on the database object
• Syntax:
$db → diconnect( );
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.
• 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]);
• 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 ]]);
• 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