TweetFollow Us on Twitter

MySQL: PHP's Perfect Partner

Volume Number: 21 (2005)
Issue Number: 3
Column Tag: Programming

Getting Started

by Dave Mark

MySQL: PHP's Perfect Partner

A few month's back, I wrote about PHP. We walked through the installation process, then went through the basics. PHP is a wonderful tool, all on its lonesome. But boy does it shine when you add a database backend to the mix. There are several database systems that work well with PHP. If you're relatively new to this business, or if your database requirements are not particularly sophisticated, MySQL is the perfect choice.

I figure, if you're reading this article, you are probably pretty new to the database universe and, therefore, MySQL is a good choice for you. But just in case you've wandered into the room with some existing expertise, but are new to open source solutions like MySQL, here's a great URL that will tell you what MySQL does differently than ANSI Standard Query Language:

http://dev.mysql.com/doc/mysql/en/Differences_from_ANSI.html

MySQL is rock-solid, and incredibly fast. There are more than five million active MySQL installations in the world and MySQL has been downloaded more than ten million times. Most are of the LAMP variety (Linux/Apache/MySQL/PHP/Perl). Lots of Mac and Windows setups as well. There are a number of benchmarks that show MySQL as the fastest such systems available, faster than the most expensive commercial DBMS's, faster even than PostgreSQL.

MySQL uses the GNU General Public License (GPL). Want to run it on your personal computer? No charge! Compare that to the $1,000 per seat licenses of some commercial DBMS apps, or the $50,000+ cost for some commercial server packages. And chances are good that if your ISP offers PHP, they'll offer MySQL as well. MySQL is not hard to find.

In this month's column, we're going to install MySQL, then make sure it's set up and ready to use. If you don't already have a reasonably recent version of PHP installed on your computer, now would be an excellent time to do so.

Installing MySQL

With each new release, the folks at MySQL AB (the corporate entity that owns the rights to MySQL) have made it easier and easier to install MySQL. In the early days of Mac OS X, installation was a bear. You had to locate the source code, build and debug, searching the net to find info on the many compile switches, till you finally made your way through a successful build. You then needed to deal with ownership issues to make sure someone couldn't creep over the net and illicitly access your tables. Working with early MySQL releases required a real pioneering spirit. Nowadays, installation is fairly straight-forward, almost trivial.

Early versions of Mac OS X required that you go through the process of creating a new user named mysql. That user was given ownership of the installed files that were not owned by Root. Most folks added the mysql account using the Accounts pane in System Preferences. That worked fine, though it created some files and directories that would only be used by a human user and added that user to the set of users presented at login.

Nowadays (since the release of Mac OS X 10.2), Apple takes care of this bit of business for you. Though they don't do the installation of MySQL, recent versions of Mac OS X create the mysql user as part of the System install. To see this for yourself, go into your Applications directory, Utilities subdirectory, and launch NetInfo Manager (in the Finder, note that shift-command-U is a shortcut to the Utilities directory).

When NetInfo Manager's main window appears, use its browser to locate the users directory. You should see a user named mysql in the second column (see Figure 1). Notice the values for home and shell. Since we won't be logging in as mysql, there's no reason for a shell and home directory.


Figure 1. NetInfo Manager, showing the mysql user.

Downloading MySQL

Though the net is full of tons of excellent MySQL resources, by far the most important is found at MySQL's official home at http://www.mysql.com. Most of the stuff we'll be interested in lies behind the Developer Zone tab at http://dev.mysql.com. To start your download decision-making process, navigate to the main download page:

http://dev.mysql.com/downloads/

Figure 2 shows the links of interest when I navigated there. Notice the Mirrors link. When you click to this page, the site will use your IP address to build a list of mirror sites it thinks are geographically close to you. You'll definitely want to check this page out if you run into problems downloading from the main site.


Figure 2. The important links on the downloads page.

Next on the list is the latest GA (Generally Available) release, followed by the previous GA release. After that is the latest preview release (essentially a beta). I would definitely stick with the most recent GA release. Click on that link.

For me, the most recent GA release was MySQL 4.1. Clicking on that link brought me to the MySQL 4.1 Downloads page. Take a minute to read the text at the top of the page:

The MySQL database server is available under the MySQL AB "dual licensing" model. Under this model, users may choose to use MySQL products under the free software/open source GNU General Public License (commonly known as the "GPL") or under a commercial license.

Click on the GNU General Public License link, then on the commercial license link. In effect, you can use the MySQL server at no cost to you, if your app is 100% GPL. This is the beauty of Open Source and the GPL model. If you are not familiar with GPL or are new to Open Source, it is well worth your time to read through the MySQL license pages. I think they are very well written and very understandable. Worth taking the time to do this.

If you are just in learning mode, the GPL license is fine. The commercial license is for people who do not want to release their source code or who find the GPL licensing rules too restrictive. The cool thing is, even the commercial license is relatively inexpensive when compared to other commercial products.

Scroll down the MySQL 4.1 Downloads page until you come to an area labeled Mac OS X downloads. As you can see in Figure 3, this part of the page is divided into 4 different sets. Two are installer-based, two are tar-ball based. There's one of each type for Jaguar and one for Panther. We're going for the Panther version with the installer package.


Figure 3. The Mac OS X download options.

Now that we've decided that, we need to decide between standard, max, or debug versions of the server software. You'd use the debug version if you were trying to debug the MySQL source itself, or if you were trying to track down a particularly knotty problem in your code and needed to see the MySQL symbols. Note that, as with any software package, there's a significant performance hit associated with the debug version.

The max version includes a number of esoteric features that you most likely won't need (the NDB storage engine, Berkeley DB storage engine, UDFs, BIG_TABLE support, etc.) The features in max tend to be beta in nature and will migrate to the standard release as they stabilize.

Bottom line, standard is the one you want. So, if you have Panther installed, you'd go to the Mac OS X downloads section, then click on the 4th overall Pick a mirror link. It'll be the first link in the subsection labeled Installer package (Mac OS X v10.3).

Once the mirror page appears, you might want to use the login link to create a new MySQL account and login. With a login, you'll be able to post questions to the forum, subscribe to the MySQL newsletter, etc. Worth it.

Once you're logged in, click on the closest mirror, then go get a nice piece of halvah. Tap, tap, tap. Done yet? Ah, there you go. If you downloaded the installer package, you'll get a .dmg file which should automatically mount as a disk image. Open the image. You'll see two packages and a readme file. The first package is the MySQL server package. The second installer, called MySQLStartupItem.pkg, installs a Startup Item which will automatically start up the MySQL server at boot time. If you are going to spend any amount of time with MySQL, you'll want this Startup Item installed.

Start with the main package. Then install the Startup Item. If you run into any problems, dig into the readme file. There's a lot of helpful info in there.

Starting the Server for the First Time

Your next step is to start the MySQL server, so we can start to play! The simplest way to do this is to just restart your computer and let the Startup Item do its thing. But it's worth seeing how this is done by hand, just to get a sense of how this works.

Fire up Terminal, then type this command:

man -ps

When you hit return at the end of the command, one page worth of the manual page for the ps command will display in the Terminal window, and a colon (:) prompt will appear at the bottom of the screen. You are looking for the list of options to the ps command, specifically descriptions of the "-a" and "-x" options. To move down a page, hit the space bar. To quit, either hit enough spaces to scroll to the end or type the letter q.

The listing for "-a" says, "Display information about other users' processes as well as your own." The listing for "-x" says, "Display information about processes without controlling terminals." Let's combine these two, like so:

ps -ax

You'll see a long scrolling list of processes. At this point, none of them should have the word mysql in them. Unless you have a really wide monitor, the commands will likely get clipped, making them hard to read. Try this command instead:

ps -ax > textfile

This does the same thing, but redirects the process listing into a text file named textfile. Unless you've specifically changed directories since you started up Terminal, the file should be in your home directory. Go into the Finder, look in your home folder, and drag textfile onto TextEdit. That's better!

Now let's start the server. At the command prompt, type:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM start

The sudo command is asking Unix to do this command as super user, or root. You should be prompted for your root password. Once you successfully enter your password, you should see this message:

Starting MySQL database server

Cool. Now do your ps -ax again and you should see two process entries that resemble these two:

  388  ??  S      0:00.03 sh ./bin/mysqld_safe --datadir=/usr/local/mysql/data --pid-file=/usr/
                                   local/mysql/data/Dave-Marks-Computer.local.pid
  408  ??  S      0:02.06 /usr/local/mysql/bin/mysqld --defaults-extra-file=/usr/local/mysql/data/
                     my.cnf --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql 
                     --pid-file=/usr/local/mysql/d

The first entry is the shell wrapper for the server daemon. Basically, this shell is acting purely as a wrapper and a safe way to communicate with the server.

The second entry is the server daemon itself. Though the daemon does all the work, you shouldn't have a need to communicate with it directly. Notice that the daemon is running with user=mysql, and not as root. This is the right way to do this. Running as root would create a dangerous security hole.

Want to shut down the MySQL server? Don't worry, it's perfectly fine to do this. Type this command:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop

Check your ps -ax again. The two processes should be gone. Go ahead and start the server again, so we can play a bit. When you restart your machine, the Startup Item issues the same command you're using to start the server:

sudo /Library/StartupItems/MySQLCOM/MySQLCOM start

Setting Up the Aliases

To help save some typing, let's set up a couple of aliases. If you are using bash shell, type these two commands:

alias mysql=/usr/local/mysql/bin/mysql
alias mysqladmin=/usr/local/mysql/bin/mysqladmin

If you are using almost any other shell, type these two commands:

alias mysql /usr/local/mysql/bin/mysql
alias mysqladmin /usr/local/mysql/bin/mysqladmin

If you are not sure which shell you are using, check the title of the Terminal window. It should say. Or just type one of the sets above. If you get an error, try the other set.

Once you've successfully executed one set or the other, add the two lines to your shell's startup file so these two aliases will be setup automatically each time you open a new Terminal window. For now, just type the commands and leave the Terminal window open so the aliases stick around.

Now, if you type mysql, you'll execute the command /usr/local/mysql/bin/mysql and when you type mysqladmin, you'll execute the command /usr/local/mysql/bin/mysqladmin. Aliases are very useful.

Setting Up the MySQL Accounts

Our last step before we actually start playing with MySQL itself is to secure the default MySQL accounts and set up a non-root account for our dabbling pleasure.

MySQL ships with two root accounts and two anonymous accounts that do not have passwords. Obviously, a dangerous situation, though one that makes perfect sense from the vendor's perspective.

There are a number of ways to do this. We'll use the mysql alias we just set up. In Terminal, type this command:

mysql -u root

This command starts up the mysql monitor using the root user. Note that this is not the same as your Unix root account. MySQL maintains its own list of users, as well as its own data security model that allows these users to own the MySQL data. Normally, when you start up the mysql client, you'd type a user name and a password. Since there is no root password yet, all we need do is specify the user name. mysql will reply as follows:

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 1 to server version: 4.1.8-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>

Notice that you are now running the MySQL monitor. The prompt at the bottom of the Terminal window is the standard MySQL prompt. You can exit the monitor by typing the command exit, followed by a return. Don't do this quite yet!

MySQL ships with a user table that holds all its account info. Let's ask the monitor to list the host and user columns in that table. At the mysql> prompt, type this command:

select host,user from mysql.user;

Notice the semicolon (;) at the end of the command. Very important!!! The semi tells the monitor that we've reached the end of the command. Here's the results on my computer:

+--------------------------- +------+
| host                       | user |
+--------------------------- +------+
| Dave-Marks-Computer.local  |      |
| Dave-Marks-Computer.local  | root |
| localhost                  |      |
| localhost                  | root |
+--------------------------- +------+

4 rows in set (0.64 sec)

mysql>

Notice that I've got 4 accounts. Two root accounts, two anonymous accounts. One of each type is for connecting from the local host. The other is for connecting from any other host.

Let's add some passwords to these accounts, keep the bad guys out! Still in the monitor, type this command, replacing xxxxx with the password you want for your local anonymous account, yyyyy with the host name from the host column above (the entry in that column that is not localhost) and zzzzz with the password you want for your second anonymous account:

SET PASSWORD FOR ''@'localhost' = PASSWORD('xxxxx');
SET PASSWORD FOR ''@'yyyyy' = PASSWORD('zzzzz');

This is the reply I got to each of these commands:

Query OK, 0 rows affected (0.00 sec)

If you'd like some evidence that you just changed the password, try this command:

select password,user from mysql.user;

Here's the result I got, after I added my passwords:

+ ----------------------------------------- +------+
|   password                                | user |
+ ----------------------------------------- +------+
|                                           | root |
|                                           | root |
|   *18796D3E621A0FB8F69503C1006CF26D337330 |      |
|   *18796D3E621A0FB8F69503C1006CF26D337330 |      |
+ ----------------------------------------- +------+
4 rows in set (0.00 sec)

Notice that the password column is stored in an encrypted form, as you might expect. Notice also that the root passwords have not been set yet. We'll do those next. Finally, note that I changed both my passwords to the same value. Good strategy? Perhaps not, but I wanted to show the consistency of the encryption. In real life, I delete the anonymous accounts completely, since I don't like them hanging around. Want to try this? Here's how you delete your anonymous accounts. Do not type these commands, unless you really don't want your anonymous accounts!!

DELETE FROM mysql.user WHERE User = '';
FLUSH PRIVILEGES;

The first command deletes the unnamed users from the user table. The second command is necessary since the table is only read when the server is first started. This prevents us having to restart the server.

Our last task is to set passwords for the root accounts. As you did before, substitute your new root password for xxxxx, your host name for yyyyy, and your second root password for zzzzz.

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('xxxxx');
SET PASSWORD FOR 'root'@'yyyyy' = PASSWORD('zzzzz');

Feel free to use this command again, to check your results:

select password,user from mysql.user;

Here's my results:

+ --------------------------------------- +------+
| password                                | user |
+ --------------------------------------- +------+
| *18796D3E621A0FB8F69503C1006CF26D337330 | root |
| *18796D3E621A0FB8F69503C1006CF26D337330 | root |
+ --------------------------------------- +------+
2 rows in set (0.00 sec)

Notice that my anonymous accounts are gone. If you somehow forget your root password after you do this, here's a link to a page that tells you how to reset the password:

http://dev.mysql.com/doc/mysql/en/Resetting_permissions.html

Till Next Month...

We did a lot this month. But the real fun comes in my next MySQL column when we really get into this stuff. We'll create tables, add data and, eventually, use PHP to pull that data out of the database and display it in a web page. Cool!

Not sure if we'll do all this next month, but I'll try. In the meantime, be sure to check out the new books at http://spiderworks.com. Rumor has it that there's a series of Tiger books in the works. Automator, Dashboard, and Spotlight. Excellent! See you next month...


Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development, including Learn C on the Macintosh, Learn C++ on the Macintosh, and The Macintosh Programming Primer series. Dave's been busy lately cooking up his next concoction. Want a peek? http://www.spiderworks.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.