Page 397 - Beginning PHP 5.3
P. 397
Chapter 12: Introducing Databases and SQL
mysql > SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
+--------------------+
2 rows in set (0.00 sec)
Be careful with statements such as DELETE and DROP , because you can ’ t undo the deletion process.
Make sure you back up your MySQL databases regularly, and before carrying out any operation that
could potentially wipe a lot of data. For information on backing up, see the “ Database Backups ” section
of the MySQL manual at http://dev.mysql.com/doc/refman/5.0/en/backup.html .
You can also alter the definition of a table, even if it already has data within it. To do this, you use the ALTER
TABLE statement. You can find out more about ALTER TABLE in the “ ALTER TABLE Syntax ” section of
the MySQL manual at http://dev.mysql.com/doc/refman/5.1/en/alter-table.html .
Connecting to MySQL from PHP
So far you ’ ve learned the theory behind relational databases and worked directly with MySQL thorough
the mysql command - line tool. Now it ’ s time to get your PHP scripts talking to MySQL.
At the time of writing, PHP provides you with two main ways to connect to MySQL databases:
❑ mysqli (MySQL improved) — This extension is specifically tied to MySQL, and provides the
most complete access to MySQL from PHP. It features both procedural (function - oriented) and
object - oriented interfaces. Because it has quite a large set of functions and classes, it can seem
overwhelming if you ’ re not used to working with databases. However, if you know you ’ re only
ever going to work with MySQL, and you want to squeeze the most out of MySQL ’ s power from
your PHP scripts, then mysqli is a good choice
❑ PDO (PHP Data Objects) — This is an object - oriented extension that sits between the MySQL
server and the PHP engine. It gives you a nice, simple, clean set of classes and methods that you
can use to work with MySQL databases. Furthermore, you can use the same extension to talk to
lots of other database systems, meaning you only have to learn one set of classes and methods in
order to create applications that can work across MySQL, PostgreSQL, Oracle, and so on
Choosing between these two extensions can be a topic of religious debate among PHP developers, which
goes to show that both approaches have their strengths and weaknesses. This book uses PDO, mainly
because it ’ s easier and quicker to learn, but once you ’ ve learned PDO you should find that you can
transfer your skills to mysqli if needed.
If you ’ ve installed PHP and MySQL using Synaptic on Ubuntu, WampServer on Windows, or MAMP on
the Mac, you should find that both the mysqli and PDO extensions are already installed. (If you need to
install PDO manually, you can find instructions at http://www.php.net/manual/en/pdo
.installation.php .)
359
9/21/09 9:11:14 AM
c12.indd 359
c12.indd 359 9/21/09 9:11:14 AM