Professional Documents
Culture Documents
Chapter 1
Chapter 1
Chapter 1
Executing query
Mini Project
Connection with PostgreSQL Database
Following PHP codes demonstrates how to set a connection with PostgreSQL Database (In Lab):
<?php
$host="host=http://192.168.16.1";
$port="port=5432";
$dbname="dbname=root";
$credentials="user=root password=";
$conn=pg_connect("$host $port $dbname $credentials") or die("could not connect");
?>
Creating a table from PHP
<?php
// $host="host=localhost";
$sql=<<<EOF
// $port="port=5432";
create table company(id int , name
// $dbname="dbname=postgres"; varchar(20));
EOF;
//$credentials= "user=postgres password=123"; $ret=pg_query($db, $sql);
//$db=pg_connect("$host $port $dbname $credentials"); if(!$ret)
echo pg_last_error($db);
$db=pg_connect("host=http://192.168.16.1 port=5432 else
dbname=ty100 user=ty100 password=123"); echo "Table created";
pg_close($db);
if(!$db)
?>
echo "unable to connect db\n";
else
echo "DB ok!!!";
Inserting records into table from PHP
$ret=pg_query($db, $sql);
<?php if(!$ret)
echo pg_last_error($db);
$db=pg_connect("host=http://192.168.16.1 port=5432
else
dbname=ty100 user=ty100 password=123"); echo "3 records added";
if(!$db)
echo "unable to connect db\n";
else
echo "DB ok!!!";
//insert the records into table
$sql=<<<EOF
insert into company values(1,'aaa'),(2,'bbb'),(3,'ccc');
EOF;
//display the records //read the records from resultset and display each record one by
$sql=<<<EOF one
select * from company; echo "\n displaying updated values";
EOF;
$ret=pg_query($db,$sql);
while($row=pg_fetch_row($ret))
if(!$ret) {
{ echo "ID= " . $row[0] . "\n";
echo pg_last_error($db); echo "Name= ".$row[1] . "\n\n";
exit; }
} echo "operation successful";
//read the records from resultset and display each record one by
one
while($row=pg_fetch_row($ret))
{
echo "ID= " . $row[0] . "\n";
echo "Name= ".$row[1] . "\n\n";
}
echo "operation successful";
//update operation
$sql=<<<EOF
update company set name='SSSS' where id=2;
EOF;
$ret=pg_query($db,$sql);
if(!$ret)
{
echo pg_last_error($db);
exit;
}
Pg_connect()
Opens a postgreSQL connection
The syntax is:
pg_connect(string $connection_string, int $flags=0)
// Execute the same prepared query, this time with a different parameter
$result = pg_execute($ dbconn, "my_query", array(“aaa aaa aaa"));
?>
pg_execute()
Sends a request to execute a prepared statement with given parameters , and waits for the result
The syntax is:
pg_execute(Connection $connection = ?, string $stmtname, array $params)