57
INSERT INTO zodiac VALUES (3,'Gemini','Twins','Mercury','air',5,21,6,21);
INSERT INTO zodiac VALUES (4,'Cancer','Crab','Moon','water',6,22,7,22);
INSERT INTO zodiac VALUES (5,'Leo','Lion','Sun','fire',7,23,8,22);
INSERT INTO zodiac VALUES (6,'Virgo','Virgin','Mercury','earth',8,23,9,22);
INSERT INTO zodiac VALUES (7,'Libra','Scales','Venus','air',9,23,10,23);
INSERT INTO zodiac VALUES
(8,'Scorpio','Scorpion','Mars','water',20,24,11,21);
INSERT INTO zodiac VALUES
(9,'Sagittarius','Archer','Jupiter','fire',11,22,12,21);
INSERT INTO zodiac VALUES
(10,'Capricorn','Goat','Saturn','earth',12,22,1,19);
INSERT INTO zodiac VALUES (11,'Aquarius','Water
Carrier','Uranus','air',1,20,2,18);
INSERT INTO zodiac VALUES
(12,'Pisces','Fishes','Neptune','water',2,19,3,20);
The specific functions required to talk to the database differ with each database, but each
follows a similar pattern. Connecting to the database returns a database connection handle.
You use the connection handle to create statement handles, which are associated with
particular queries. A query statement handle then gets the results of that query.
This example retrieves all the rows from the
zodiac
table with Oracle, using the OCI8
interface:
if (! $dbh = OCILogon('david', 'foo!bar','ORAINST')) {
die("Can't connect: ".OCIError());
}
if (! $sth = OCIParse($dbh,'SELECT * FROM zodiac')) {
die("Can't parse query: ".OCIError());
}
if (! OCIExecute($sth)) {
die("Can't execute query: ".OCIError());
}
$cols = OCINumCols($sth);
while (OCIFetch($sth)) {
for ($i = 1; $i <= $cols; $i++) {
print OCIResult($sth,$i);
print " ";
}
print "\n";
}
The
OCILogin( )
function connects to a given Oracle instance with a username and
password. You can leave out the third argument (the instance) if the environment variable
ORACLE_SID
is set to the desired Oracle instance. A statement handle is returned from
OCIParse( )
, and
OCIExecute( )
runs the query. Each time
OCIFetch( )
is called, the
next row in the result is retrieved into a result buffer. The value of a particular column of the
current row in the result buffer is retrieved by
OCIResult( )
.
Here's the same example using PostgreSQL: