Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml


Dezvoltarea unui site PHP cu baze de date PostgreSQL

php



+ Font mai mare | - Font mai mic



Dezvoltarea unui site PHP cu baze de date PostgreSQL

Pentru inceput vom lua in discutie modul de instalare si configurare a unui server WEB (Apache) cu un modul de PHP si cu serverul de baze de date PostgreSQL. Cu aceste produse (gratuite), putem construi site-uri cu continut dinamic preluand date din baza de date PostgreSQL, cu ajutorul limbajului de scripting PHP.



Pentru realiza acest lucru trebuie sa avem instalat Linux-ul si pachetele cu surse ale celor trei produse. Pentru a instala Apache 1.3.x ,PHP 4.0.x si PostgreSQL 7.0.x vom descarca cele trei produse astfel:

# APACHE

# PHP

# POSTGRESQL

de la adresele: APACHE - https://www.apache.org, PHP - https://www.php.net, POSTGRESQL - https://www.postgresql.org

Vom instala pachetele in directoare astfel:

APACHE in /usr/local/apache

PHP ca modul al APACHE si POSTGRESQL in /usr/local/pgsql/

directorul de web va fi: /usr/local/apache/htdocs

Instalarea server-ului POSTGRESQL

Pentru inceput vom crea un cont pentru server-ul de baze de date astfel:

# su

# /usr/sbin/adduser postgres

# passwd postgres

# exit

Dupa aceasta vom creea directoarele necesare pentru a putea instala server-ul POSTGRESQL cu permisiunile adecvate:

# su

# cd /usr/src

# mkdir pgsql

# chown postgres:postgres pgsql

# cd /usr/local

# mkdir pgsql

# chown postgres:postgres pgsql

# exit

Realizam compilarea si instalarea:

# su postgres

# cd /usr/src/pgsql

# tar xzvf /local/download/postgres-7.0.x.tar.gz

In functie de versiune configure poate fi in directorul postgres-7.0.x/src sau poate fi in postgres-7.0.x. Vom vedea acest lucru dintr-o alta consola si apoi realizam schimbarea de director.

# cd /usr/src/pgsql/postgresql-7.0.x/src

# ./configure --prefix=/usr/local/pgsql --with-tcl --with-perl

# gmake all > make.log 2>&1 &

# tail -f make.install.log

# exit

Vom configura sistemul astfel incat sistemul sa stie unde sunt bibliotecile; vom actualiza fisierul /etc/ld.so.conf

# su>

# echo /usr/local/pgsql/lib >> /etc/ld.so.conf

# /sbin/ldconfig

# exit

De asemenea vom actualiza fisierul ~/.bash_profile al contului de administrator al serverului POSTGRESQL.

# su postgres

Apoi editam fisierul ~/.bash_profile si adaugam urmatoarele linii:

PATH =$PATH:/usr/local/pgsql/bin

MANPATH=$MANPATH:/usr/local/pgsql/man

PGLIB=/usr/local/pgsql/lib

PGDATA=/usr/local/pgsql/data

export PATH MANPATH PGLIB PGDATA

# exit

Odata ce am instalat si configurat serverul de baze de date POSTGRESQL trebuie sa initializam si sa pornim server-ul astfel:

# su postgres

# initdb

# cd

# nohup postmaster -i > pgserver.log 2>&1 &

Presupunem ca avem o baza de date numita Prim cu o tabela numita Test. O vom crea, dupa ce am pornit server-ul cu comanda de mai sus:

# createdb Prim

# psql Prim

Prim=> create table Test(Nume varchar(20),Prenume varchar(20),

Prim-> Email varchar(30));

Astfel am creat baza de date Prim si in cadrul ei tabela Test. Acum vom introduce cateva inregistrari

Prim=>INSERT INTO Test VALUES('Ionescu','Ion','ionescu@feaa.ro');

Prim=>INSERT INTO Test VALUES('Popescu','Marin','popescu@feaa.ro');

Prim=>INSERT INTO Test VALUES('Marin','Adrian','marin@feaa.ro');

Vom crea user-ul nobody cu comanda. createuser nobody o vom dati dupa ce am intrat ca utilizator postgres si am pornit server-ul cu comanda amintita mai sus (nohup postmaster).

# createuser nobody

Vom seta drepturi de extragere pentru utilizatorul folosit de server-ul de web Apache.

# su postgres

# psql Prim

Prim=> GRANT SELECT ON Test TO nobody;

Prim=> z

Prim=> q

# exit

Instalarea server-ului de web APACHE cu PHP ca modul si cu suport de baze de date PostgreSQL. Pentru a instala APACHE cu PHP introducem urmatoarele instructiuni:

# su

# cd /usr/src

# tar xzvf /local/download/apache_1.3.x.tar.gz

# tar xzvf /local/download/php-4.0.x.tar.gz

# cd apache_1.3.x

# ./configure --prefix=/usr/local/apache

# cd ../php-4.0.x

# ./configure --with-pgsql=/usr/local/pgsql

--with-apache=../apache_1.3.x --enable-track-vars

--enable-sysvsem --enable-sysvshm

--enable-url-includes

# make

# make install

# cd ../apache_1.3.x

# ./configure --prefix=/usr/local/apache

--activate-module=src/modules/php4/libphp4.a

# make

# make install

# cd ../php-4.0.x

# cp php4.ini-dist /usr/local/lib/php4.ini

# exit

Vom configura serverul de web APACHE. Aceasta se face prin modificarea catorva setari in fisierul /usr/local/apache/conf/httpd.conf

In acesta trebuie modificate directivele: ServerAdmin , ServerName, DocumentRoot si directiva Directory dar si

AddType application/x-httpd-php4 .php

DirectoryIndex index.htm index.php

Toate sunt bine comentate in fisierul httpd.conf din directorul conf al server-ului APACHE.Comentariile incluse in fisier dispun de explicatii detaliate pentru a putea face corect aceste setari. Dupa ce am facut toate setarile de rigoare nu ne ramane decat sa pornim server-ul.

Pornirea serverului APACHE se face astfel:

# su

# cd /usr/local/apache/bin

# ./apachectl start

Oprirea server-ului se face tot cu comanda apachectl astfel:

# ./apachectl stop

Dupa ce am instalat toate cele necesare sa vedem daca PHP-ul conlucreaza bine cu server-ul Apache.Trebuie sa cream un fisier pe care il numim index.php, iar in acest fisier vom scrie urmatorul cod PHP:



<?php

echo phpInfo();

?>

Acest fisier il salvam in directorul pe care l-am setat la directiva DocumentRoot in fisierul httpd.conf sub numele index.php dupa care il apelam din browser astfel: https://localhost/index.php

Ruland scriptul PHP vom obtine o pagina cu toate setarile server-ului Apache si cu modulele aferente lui. Odata ce am vazut ca PHP-ul merge impreuna cu Apache-ul, trebuie sa vedem cum merg toate impreuna adica Apache-ul cu PHP-ul si cu PostgreSQL.

Sa presupunem ca avem baza de date Prim cu tabela Test, care are trei campuri si anume Nume,Prenume,Email.

Vom scrie urmatorul script PHP care se conecteaza la PostgreSQL:

<HTML>

<HEAD>

<TITLE></TITLE>

</HEAD>

<BODY>

<?php

$conexiune = pg_connect('','','','','Prim');

if(!$conexiune)

$strsql = 'SELECT * FROM Test ORDER BY Nume;';

$rez = pg_Exec($conexiune,$strsql);

$num = pg_NumRows($rez);

for($j=0;$j<$num;$j++)

pg_close($conexiune);

?>

</BODY>

</HTML>

Acest script de mai sus ar trebui sa listeze toate inregistrarile din tabela Test care face parte din baza de date Prim.

Detalii

pg_connect( host, port [,options [, tty ]], database );

Connect-string Property

Environment Variable

Example

User

PGUSER

user=korry

Password

PGPASSWORD

password=kim

Dbname

PGDATABASE

dbname=accounting

Host

PGHOST

host=jersey

Hostaddr

PGHOSTADDR

hostaddr=127.0.0.1

Port

PGPORT

port=5432

Primii doi parametri sunt intotdeauna considerati ca numele masinii si numǎrul portului. Ultimul parametru este intotdeauna tratat ca numele bazei de date.

pg_connect( host, port, database );

pg_connect( host, port, options, database); + listǎ de optiuni ale serverului

pg_connect( host, port, options, tty, database ); + numele tty-ului sau fisierului in care serverul PostgreSQL va scrie informatille de debug

Este recomandat sǎ nu specificǎm utilizatorul si parola utilizand forma multiparametru al functiei pg_connect(). Am putea utiliza variabilele de mediu cu PHP, care sunt variabilele din mediul serverului web. Este necesar sǎ setǎm PGUSER si PGPASSWORD inainte de a porni serverul web. O altǎ variantǎ este utilizarea functiei PHP putenv().

putenv( 'PGUSER=korry' );

putenv( 'PGPASSWORD=kim' );

$db_handle = pg_connect( NULL, NULL, NULL, NULL, 'movies' );

Este necesarǎ stabilirea conexiunii cu baza de date intr-un script PHP distinct si mutarea scriptului in afara structurii de directoare a serverului web.

include( 'secure/my_connect_pg.php' );

<?php

// File: my_connect_pg.php



function my_connect_pg( $dbname )

?>

pg_Exec <=> pg_execute - trimite o cerere pentru executia unei declaratii pregatite anterior cu parametrii specificati si asteapta rezultatul.

pg_NumRows <=> - returneaza numarul de linii intr-un result


Use PostgreSQL and PHP on Windows

Some people think it is incredibly difficult to run PostgreSQL on Windows, because there's no easy-to-use Win32 installer (at the time of writing, 7.3.4. is the latest version). Users have to install some sort of unix [3] emulator first, and run the database system on this 'platform'.

The PostgreSQL Technical Documentation Site says, 'The main PostgreSQL project plan is to add support for a native Windows version with our 7.4 release. This will probably be released in the middle of 2003' I haven't seen this release yet? maybe late 2003? However, what this means is that, in the future PostgreSQL will be an even more appealing choice than MySQL!

Build a database driven Website with PostgreSQL? Why would you do such a thing? Isn't the rule that if you?re using PHP, your database is MySQL -- period!?

Well, in my case, it was until I was assigned the task to convert an ASP [4]/MSSQL solution to PHP/PostgreSQL. The reasons for the change?

we (the assigner) didn't want to use Microsoft products any longer (due to the associated licensing cost)

we wanted database features that weren?t present in MySQL (foreign keys etc)

To me, it also seemed to be a good idea to have both the old ASP stuff and the new PHP install on the same (Windows) development machine when we performed this 'translation'. Another good reason to try the Windows, PostgreSQL, and PHP combination is that it's always fun to find the answer to that age-old question, 'How difficult can it be?'

I must admit up-front that I'm a Microsoft-indoctrinated sort of developer. Primarily I use MSSQL, less often MySQL, and almost never PostgreSQL. It was the same with operating systems; 90% of the time I used Windows, 10% Linux [5]. Despite those facts, my move to PostgreSQL ended happily. And if it was doable for me, then it is for you, too.

For more reading on alternatives to MySQL, see Wayne Luke's article '>Moving Beyond MySQL - High End Database Solutions [6].

The PHP Anthology: Volume I & II

Save hours researching solutions to common problems

Explore real-world Object Oriented Programming with PHP

Develop secure, reliable PHP Applications

Cut down on wasted development time with enterprise practices

Download 4 Sample Chapters FREE

Note that this tutorial assumes you have read chapter one in Kevin Yank's excellent Build Your Own Database Driven Website Using PHP and MySQL, or some other tutorial that explains how to install Apache [7] and PHP on Windows. More importantly, I assume that after learning this process, you have successfully installed a Web server with PHP 'plug-in'.

Let's begin!

Cygwin Installation

The first task is to download and install Cygwin [8], which is a linux-like environment for Windows. At the time of writing, the latest version of Cygwin is 1.5.5. It's not a bad idea to rename setup.exe to cygwin_setup.exe -- this way, the file will be easier to locate when you want to add/remove/update Cygwin components later.

Naturally, you should be logged in as a user belonging to the group Administrators when you launch the setup program.

The Cygwin Net Release Setup Program will ask you the following eight questions:

Disable Virus Scanner?

As some antivirus programs may cause problems during the Cygwin installation, you have the option to disable the virus scanner temporarily. In most cases, the default option Leave Virus Scanner Alone works. (If no antivirus program is detected, then -- sooner or later ? you?ll encounter another type of problem)

Choose Installation Type

Select Install from Internet.

Choose Installation Directory

You can use the default options here too, unless you have some really good reason not to designate C:cygwin as Root Directory, Install For All Users and select Unix as Default Text File Type.

Select Local Package Directory

The folder you specify here is the location where the downloaded installation files will be saved. Enter the path of your choice, e.g. E:cygwinfiles.

Select Connection Type

Here you select the appropriate connection type; the default option is Direct Connection. Most likely, your antivirus/firewall program will pop up after you click Next, to check if you want to allow cygwin_setup.exe to access the Internet. Yes, that's exactly what we want!

Choose Download Site

Select any site from the list, preferably one that?s close to you. Depending on your connection speed, it will take a moment or two before the next screen appears.

Select Packages

You only need to make two additions to the by-default selected packages; cygrunsrv (category Admin) and postgresql (category Database). Cygrunsrv is an NT/W2K service initiator, and PostgreSQL is well, you know what it is. At the time of writing, the version of the Database Management System is 7.3.4.

If you?re a control freak, verify that cygipc (category Devel) is among the pre-selected packages. Cygipc provides IPC (InterProcess Communication) support for Cygwin, but will eventually be replaced by the 'cygwin-daemon'. At the time of writing, PostgreSQL depends on cygipc.

Now you can take a break and drink some coffee while the files are downloaded and installed.

Create Icons

Well, this last screen is quite self-explanatory.

Click Finish, and smile happily when you see

Installation complete!

Installing Services

Installation complete? No, not yet. The files are there, somewhere in c:cygwin or wherever you chose to put them. Now you must install services, create a postgres user and initialize PostgreSQL.

These instructions are based on the postgresql-7.3.4.README file, written by Jason Tishler, which is located in /usr/doc/Cygwin. In that file, you can find instructions for the Basic Cygwin PostgreSQL Installation, which is your only option if you?re running Windows 95/98/ME (but if you ask me, the only option for someone running Windows 9x is: upgrade!).

Start your newly-installed Cygwin Bash Shell and complete these steps:

Install ipc-daemon2 as an NT service

As you remember from the Cygwin installation, Cygipc is the interprocess communication daemon that PostgreSQL depends on.

ipc-daemon2 --install-as-service

If you are a curious person (like me), launch the Services MMC Console Snap-in in Windows (services.msc) and verify that you have a new service called Cygwin IPC Daemon 2 in the list.

Create a new user account

A quote from the PostgreSQL documentation states: 'It is advisable to run PostgreSQL under a separate user account'.

So, let's add a new user, and due to lack of imagination, call the new user 'postgres'. Note that you should replace ******** below with the password you want to use for postgres.

You can issue one single net user command with all the options (fullname, comment, homedir) on one line, but I've written them as separate commands here to make the text more readable. To see the net user syntax, type ';net [9] user /?'.

net user postgres ******** /add

net user postgres /fullname:postgres

net user postgres /comment:'PostgreSQL User Account'

net user postgres /homedir:'$(cygpath -w /home/postgres)'

If you feel like it, check in the Local Users and Groups MMC Snap-in (compmgmt.msc) that postgres has joined the team. There should also be a newly created folder called C:cygwinhomepostgres.



Update the file /etc/passwd

mkpasswd -l -u postgres >> /etc/passwd

The command above, translated into English, means: append information for the specified user postgres to /etc/passwd. Please note that there should be two greater-than characters!

Grant postgres the right to log on as a service

Why? This is rather obvious; postgres is the user that should run the postmaster service later. Launch the Local Security Settings MMC Snap-in (secpol.msc) and add postgres to the list of users that can log on as a service, under Local Policies User Rights Assignment.

Create a data directory

This is where PostgreSQL will store the data, of course.

mkdir /usr/share/postgresql/data

Make postgres the owner of the data area

Another natural thing; no other than postgres should own the data directory, of course.

chown postgres /usr/share/postgresql/data

Later, the initialization process will revoke permissions for everyone except postgres.

Install postmaster as an NT service

Postmaster is the name of the PostgreSQL server, located in /usr/bin. Postmaster will also be the name of the service you create (who said 'lack of imagination'?!).

cygrunsrv -I postmaster -p /usr/bin/postmaster

-a '-D /usr/share/postgresql/data -i'

-y ipc-daemon2 -s INT -u postgres ?o

Note that the command has been divided into three lines here to make it more readable, but you should write everything on one line.

Whoa! What do all these options mean? Translation: Install (-I) a new service called postmaster, with application path (-p) /usr/bin/postmaster, arguments (-a) '-D /usr/share/postgresql/data -i', which in turn means that postmaster should use /usr/share/postgresql/data as data directory (-D) and TCP/IP connections (-i) should be enabled.

Further on, the postmaster service depends on (-y) another service called ipc-daemon2, sends the signal INT when terminated (-s), is run by the user (-u) postgres and stops during system shutdown (-o).

Cygrunsrv will ask you (twice) for the password interactively.

To see the cygrunsrv syntax, type 'cygrunsrv -h'. If you want to learn more about options for the PostgreSQL server, type 'postmaster --help'.

Now, if you look in the Services MMC Console Snap-in (services.msc), you will see yet another service in the list. Double-click on postmaster to review the different properties you just assigned (Log On, Dependencies etc.).

Create a Database Cluster

Before you can start postmaster (the service), the database storage must be initialized. You must run the command initdb logged in as the postgres user.

Note: log in as the postgres user! To avoid all possible problems, log off from Windows, and log in again, but this time as postgres (i.e. don't use the su command in cygwin to switch user).

Start the Cygwin Bash Shell and enter:

initdb -D /usr/share/postgresql/data

The switch -D is used to indicate where the data area is located (quite easy to guess, wasn't it?). Now you can log out, and log in as yourself again.

Test to see whether PostgreSQL is working

Finally, you should now be able to connect to PostgreSQL. Launch Cygwin, connect as the user postgres and use the database template1, created by initdb.

psql -U postgres template1

The database template1 is, as you understand, the default template that?s copied when you create a new database using the createdb command or the CREATE DATABASE statement.

If, for some reason, you receive a message like 'psql: could not connect to server', start the postmaster service with this command:

net start postmaster

To learn more about how to use psql, the PostgreSQL interactive terminal, type 'psql --help'. I think we can define a general rule here: any command plus '-- help' will show you some helpful text!

Connect to PostgreSQL from PHP

Open your php.ini file (most likely located in c:winnt), find the section called Dynamic Extensions and un-comment the line that contains 'extension=php_pgsql.dll'. Save and close php.ini and restart Apache. If the Web server complains and says it's unable to load the dynamic library, you probably have entered the wrong path for extension_dir in php.ini (section Paths and Directories). Another possible -? though unlikely -- cause is that the file php_pgsql.dll isn't present in the extensions directory.

Now you should be able to run the following little PHP script:

<?

$conn = pg_connect('host=localhost [10]

port=5432

dbname=template1

user=postgres

password=********');

$sql = 'SELECT current_date AS today;';

$result = pg_query($conn, $sql);

$row = pg_fetch_object($result, 0);

echo 'Today is: ' .$row->today;

?>

The script isn't too exciting, but at least it shows you how to connect to the database and execute a query.

Note that the code above isn't supposed to be an example of best practices in PHP. Of course you should add error handling, use pg_close() to close the connection explicitly when you are done etc. The database template1 should be used as a template (what else?) for the new database(s) you create for your application(s), and you should create new users and give them appropriate privileges (i.e. don't connect as postgres).

For more information on how to create databases, users, tables etc., see the PostgreSQL documentation [11].

For more reading on how to use PHP's PostgreSQL functions, see the articles Migrate your site from MySQL to PostgreSQL Part 1 [12] and Part 2 [13], and of course the PHP documentation [14].

Useful Tools

Command line SQL can be fun if you are a real geek, but to manage the database(s), I used Aqua Data Studio v 3.0 from AquaFold, Inc [15]. Well, it isn't MSSQL Enterprise Manager, or even MySQL Control Center, but it gives you a better view of the objects than you?d get through the psql interactive terminal. One nice feature of Aqua Data Studio is that you can connect to, and view in the same tree structure, other types of databases; MySQL, MSSQL, Oracle, and more.

If you just want to manage your PostgreSQL database, pgAdmin [16] is the tool for you. I guess 'tens of thousands of developers worldwide' can't be totally wrong. Remember, this isn't a software review, hence the few words. Another option is to use MS Access (after all, you?re running Windows, so there's a high probability you also have MS Office) as a front-end for PostgreSQL, but then you have to install the psqlODBC driver [17] first.

Since you have Apache and PHP, you could use phpPgAdmin [18], a browser based tool that?s not completely dissimilar to phpMyAdmin for MySQL.

Epilogue

Hopefully, you found this article interesting, you couldn't wait to try the installation procedure yourself, and now you are busy absorbing knowledge about PostgreSQL (see links above). If you are a MySQL user, I'm sure you will 'discover' useful functionality missing in MySQL. If you are a MSSQL user, you will appreciate that PostgreSQL is available free of charge, yet full of powerful features.

Do note that there's no uninstaller included in the Cygwin setup. If you want to remove the things you?ve added after reading this tutorial, you?ll have to manually delete

HKEY_CURRENT_USERSoftwareCygnus Solutions

HKEY_LOCAL_MACHINESOFTWARECygnus Solutions

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesipc-daemon2

HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicespostmaster

the postgres user account

the Cygwin installation directory (don't forget; you have to become owner of the data directory before you can delete it)

the local packages directory





Politica de confidentialitate | Termeni si conditii de utilizare



});

DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 1634
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved