PHP-MySQL developer transitioning to PostgreSQL. What do I need to know? - php

I've developed most of my applications in PHP-MySQL, because it was quick and easy. Now, with more complex applications and I'm wondering if MySQL is a good choice. I'll be building my latest application with PostgreSQL. What are things I need to be aware of? What was I missing when using MySQL?

This Wiki page is a good start:
http://wiki.postgresql.org/wiki/Converting_from_other_Databases_to_PostgreSQL#MySQL
Edit: to answer the second part (things you have been missing):
generate_series()
deferrable constraints
check constraints
recursive queries
table functions
common table expressions
windowing functions
function based index
partial indexes
full text search on transactional tables
GIS features on transactional tables
MINUS or INTERSECT operator
Edit2: things you might find problematic
PostgreSQL is far more strict in terms of matching datatypes (where character_column = 1 will throw an error)
no cross-database queries, if you need something like that, mapping MySQL databases to PostgreSQL schemas is probably easier
No variables in regular SQL statements (set #nr = 1; select #nr + 1...)

Read the fine manual, chapters 2 - 9 are the most important ones to start with.
Make sure you do some proper error handling in PHP and read all error messages carefully: In most cases it tells you exactly what went wrong and how to fix it. Appendix A has all error messages and codes, you need them. PostgreSQL doesn't accept wrong input or queries, it's correct or you get an error to start debugging. And that's good, less bugs and less time you will spend on scripting.
pg_query_params() and pg_fetch_all() are some great functions in PHP to interact with PostgreSQL, check the PHP manual.

Related

PHP MYSQL Create Database with Database Variable

I've created following code & I can't seem to find out what's wrong with it, any help would be greatly appreciated.
<?php
$con = mysql_connect("host","user","password");
mysql_select_db("Stores", $con);
$street = mysql_query("SELECT Street FROM Sports WHERE Name = 'Nike'");
if (mysql_query("CREATE DATABASE $street", $con))
{
echo "Success";
}
else
{
echo "Fail";
}
mysql_close($con);
i keep getting fail, can anyone point me in the right direction?
There are many problems with this code:
this may not be very relevant at first, but the php mysql extension is marked deprecated, please switch to mysqli or better still, PDO as is also indicated in the official documentation. Deprecated means that it's only there to support legacy code (and that implies that it should not be used in new code) and that it will disappear at some point in the future. I suggest PDO as it's a much more mature, flexible and universal database interface, if you are going to invest time in learning something, PDO is definitely the way to go. Pay special attention to prepared statements, they will help you avoid all kinds of problems without having to fumble with the various escape functions.
mysql_query returns a query result (as a resource) that you should read eg with some kind of fetch command - see the doc for PDO's query() method here
I haven't got the slightest idea why you would want to create a new database on your server named after the street you found via a query? You should probably explain what your intention is, I'm quite sure this isn't going to do what you want it to do.
EDIT based on the comments:
For me the main advantages of switching to PDO are
future-proofness: with the mysql_ extension you'll upgrade php one day and the extension will be gone, forever. That won't happen with PDO anytime soon.
support for multiple databases: traditionally each database brand was served by its own proprietary extension in mysql. PDO unifies all these extensions which means that with 1 API you can work with most common databases in existence. Note that it doesn't iron out dialect differences between these databases, but having one API for them all is definitely a big plus.
PDO actively encourages you to use prepared statements, which are generally recognized as a bulletproof yet simple protection against all kinds of security issues like SQL injection - no need for all that escaping nonsense that you'll need to do to make regular SQL statements somewhat safe.
Regarding the remark about creating a database for each user, I really think you need to go through some introductory material wrt relational databases. Most commonly an application is backed by one database containing in most cases a fixed set of tables (eg store, customer, order, orderitems) with relations between them. Eg a store has many customers, each of which have one or more orders, each of which contain one or more items. All data is fetched by utilizing these relations via queries, using joins to extract for example all items belonging to one order, or to list all orders associated with one customer. The important thing here is that in all but the most exceptional cases there 's just one table per data type. That is, all customers are stored in just one table, all orders are stored in just one table, and so on.
I have no time to read all of it, but databaseprimer.com might be helpful to get you started with these concepts.
mysql_query will return a resource. You have to fetch the data first using mysql_fetch_assoc($query)
Add this line after your query:
$fetch = mysql_fetch_assoc($streets);
Then in your second query change $streets to $fetch['street'].

Is there a mysqlfiddle?

I've grown quite fond of jsfiddle and how easy it is to use.
Does anyone know of something that works with mysql and maybe php mixed in?
You might be interested in my site: http://sqlfiddle.com. I've built it only recently, but it does support a decent range of database types (including MySQL) and has gotten a fair amount of use lately here on StackOverflow (see the mention on the sql wiki). You can build indexes, and views, and do nearly anything you would normally want to do within a database. Be sure to check out some of the sample fiddles, or see how various other SO users are using it:
MySQL query - optimized -> http://sqlfiddle.com/#!2/1fde2/39
Multilevel Users in the Database table -> http://sqlfiddle.com/#!2/0de1f/7
How to compare a value with a csv value in mysql? -> http://sqlfiddle.com/#!2/b642c/4
I guess I should mention that one other potential useful feature for SO would be that each query displays its execution plan, so if multiple people submitted answers to a sql question, you could easily evaluate their efficiency and then upvote/accept accordingly.
Try SQLize.
It has some annoying limitations, like the inability to create views, but overall I find it very useful. (Tip: CREATE INDEX also doesn't work, but you can still create indexes inside CREATE TABLE.)

Syntax differences between mysql, sqlite and pgsql

I'm creating a tiny activerecord library using PDO and I'm planning to support MySQL, Sqlite and PgSQL.
My question is how I can be sure that the query string works with all adapters? There will mostly be CRUD statements with some joins etc. Is there a standard I can follow that works for all of these?
Thanks
/ Tobias
EDIT: Thanks for all your answers but my question was more about the SQL 'syntax' differences between them.
If you want to write your own DB layer, I'd suggest you:
Use placeholders, if you aren't already. They add security too.
Use bindParam/bindValue with value type (e.g. BOOLEANS don't exist in SQLite but work if bound with PARAM_BOOL)...
Use stored procedures from MySQL, create matching names in PostgreSQL, and define them in SQLite with sqliteCreateAggregate/sqliteCreateFunction.
Do all parameter checking in PHP, because SQLite won't do any (e.g. validate date variables)...
Use InnoDB for MySQL to get transactions.
Note: By supporting these vastly different RDBMs, you're demoting the database to just a data store. Keep in mind that SQLite is very limited. It does not have native data types save from number/string. E.g. it's missing date handling and intervals, and so on. All three databases support transactions, which are essential for data integrity when the integrity is maintained outside the DB.
Edit: Removed mention of MySQL triggers, which are availabe for 5.0.
Here you have a simple introduction to zend_db_adapter - i think you want something similar (I posted this just as a example to see how others resolve the problem you have)
My choice for this kind of issues would be ADOdb. While I never actually used it with PostgreSQL, it just saved my sanity in a project that happened to be born with MySQL and then migrated to SQL Server, to SQLite and back to SQL Server.

Running a list of MySQL queries without using exec()

I've got a site that requires manual creation of the database tables on install. At the moment they are saved (along with any initial data) in a collection of .sql files.
I've tried to auto-create using exec() with CLI MySQL and while it works on a few platforms it's fairly flakey and I don't really like doing it this way, plus it is hard to debug errors and is far from bulletproof (especially if the MySQL executable isn't in the system path).
Is there a better way of doing this? The MySQL query() command only allows one sql statement per query (which is the sticking point).
MySQLi I've heard may solve some of these issues but I am fairly invested in the original MySQL library but would be willing to switch provided it's stable, compatible and is commonly supported on a standard server build and is an improvement in general.
Failing this I'd probably be willing to do some sort of creation from a PHP array/data structure - which is arguably cleaner as it would be able to update tables to match the schema in situ. I am assuming this may be a problem that has already been solved, so any links to any example implementation with pro's/con's would be useful!
Thanks in advance for any insight.
Apparently you can pass 65536 as client flag when connecting to the datebase to allow multi queries, e.g. making use of ; in one SQL string.
You could also just read in the contents of the SQL files, explode by ; if necessary and run the queries inside a transaction to make sure all queries execute properly.
Another option would be to have a look at Phing and dbdeploy to manage databases.
If you're using this to migrate data between systems, consider using the LOAD DATA INFILE syntax (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) after having used SELECT ... INTO OUTFILE (http://dev.mysql.com/doc/refman/5.1/en/select.html)
You can run the schema creation/update commands via the standard mysql_* PHP functions. And if the query() command as you call it will allow only one statement, just call it many times.
I really don't get why do you require everything to be in the same call.
You should check for errors after each statement and take corrective actions if it fails (unless you are using InnoDB, in which case you can wrap all statements in a transaction and rollback if it fails.)

What databases used with PHP share the same (or most) of the SQL syntax?

I've read that although SQL is meant to be standardised, it is implemented different etc with different databases. I have only ever used MySQL for databases.
What I would like to know is what other databases share the same syntax? I am using PDO now, and I would like to set a flag to allow the user to specify which database they would like to use.
I would be interested in knowing which are the 'safe' databases that will handle most (if not all) my general MySQL queries. Mainly SELECT, INSERT, UPDATE, DROP, DELETE.
Thanks
There are several revisions of a such called ANSI SQL.
All major database engines (that is Oracle, MS SQL, PostgreSQL and MySQL) should (should) in theory support SQL-92.
This includes everything you've mentioned: SELECT, INSERT, UPDATE, DROP, DELETE, as long as you don't use complex clauses with them.
In practice:
Not all databases support the full set of SQL-92.
Writing cross-platform SQL even in SQL-92 requires lots of testing.
Platform independency in SQL ends when you insert your 1001st row and need to optimize you queries.
If you browse a little over StackOverflow questions tagged SQL, you will see that most of them say "help me to optimize this query", and most answers say "use this platform dependent hack"
You will find that some database store datatypes differently, for example, mysql stores Booleans as 1 and 0 and postgres stores them as 't' and 'f'.
As long as your database classes are aware of the need to convert data, you should be fine, probably 96.3482% of everyday CRUD will work pretty well across the board.
Even if you create database classes that directly call PDO, you can later on add some logic for data translation or query modification.
You could use the database abstraction layer ADOdb. (its got what plants crave)
I'd suggest making sure that your customers actually give a crap about which database they need to run before you spend a lot of time developing functionality you may not need.
A standardized SQL92 is pretty much the same in all RDBMS. The differences are in parts, that the standard doesn't define, like for example LIMIT or datetime handling functions and of course procedural languages.
As for DBs popular with PHP: it not that hard make SQL portable between MySQL, SQLite and PostgreSQL. It won't be that easy with Oracle, Sybase and DB/2.

Categories