PostgreSQL is another popular database you can use with PHP.

If you are already familiar with how to interface with MySQL in PHP, then the following chart should make the conversion to PostgreSQL much easier.


Connecting: mysql_connect takes three arguments (server, username, password) while pg_connect takes a single connection string argument.
mysql_connect Example: $db = mysql_connect('localhost', 'mysql_user', 'mysql_pass');
pg_connect Example: $db = pg_connect('host=localhost user=pg_user password=pg_pass dbname=my_database');
Database Selection: In MySQL, you have to separately specify the name of the database you wish to connect to, while in PostgreSQL it is built into pg_connect's connection string.
Querying: mysql_query and pg_query behave in the same manner.
mysql_query Example: $grab_people = mysql_query("SELECT * FROM people WHERE id_num = 3761832");
pg_query Example: $grab_people = pg_query("SELECT * FROM people WHERE id_num = 3761832");
Fetching Associative Results: mysql_fetch_assoc and pg_fetch_assoc behave in the same manner.
mysql_fetch_assoc Example: $person = mysql_fetch_assoc($grab_people);
pg_fetch_assoc Example: $person = pg_fetch_assoc($grab_people);
Grabbing Errors: While MySQL makes use of mysql_error, PostgreSQL uses pg_last_error.
mysql_error Example: $error = mysql_error;
pg_last_error Example: $error = pg_last_error;
Closing Database Connection: mysql_close and pg_close behave in the same manner.
mysql_close Example: mysql_close($db);
pg_close Example: pg_close($db);
Freeing Results: mysql_free_result and pg_free_result behave in the same manner.
mysql_free_result Example: mysql_free_result($grab_people);
pg_free_result Example: pg_free_result($grab_people);

Full MySQL Example

 $db = mysql_connect('localhost', 'mysql_user', 'mysql_pass');
 $grab_people = mysql_query("SELECT * FROM people WHERE id_num = 3761832");
 $person = mysql_fetch_assoc($grab_people);
 $error = mysql_error;
 if($error != ) { print $error; }

Full PostgreSQL Example

 $db = pg_connect('host=localhost user=pg_user password=pg_pass dbname=my_database');
 $grab_people = pg_query("SELECT * FROM people WHERE id_num = 3761832");
 $person = pg_fetch_assoc($grab_people);
 print pg_last_error;

For More Information

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.



Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.

Manage research, learning and skills at Create an account using LinkedIn to manage and organize your omni-channel knowledge. is like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us