Web Shoppe
Home | Coding | PHP | PHP and MySQL

PHP and MySQL

After using PHP for things like mail forms and dynamic URLs, you'll soon want to move on to more advanced things, like guestbooks, message boards and shoutboxes. These things, however, require data storage, and sometimes a lot of it. While you can store your data in a text file, it is much more simple and efficient to use a MySQL database.

MySQL is a SQL (Structured Query Language) database server. A SQL database is a very powerful tool for storing, using and retrieving large (and small) amounts of information (data). In this tutorial we will be using PHP to insert and read data from a MySQL database.

First we need to connect to the database with PHP. To do this, we start off by defining a few variables:

$server = "localhost";	// server to connect to.
$database = "mydata";	// the name of the database.
$db_user = "myusername";	// mysql username to access the database with.
$db_pass = "mypassword";	// mysql password to access the database with.
Remember that everything following these // double slashes is just a comment or a note to yourself.

$server is the location of the MySQL server. Sometimes it will be a name or an IP, but usually it will be "localhost." localhost means that it is on the same computer as the script.
$database is the name of the database you will be using. Usually this is created by your host upon request, or you can do it yourself through your control panel.
$username and $password are your MySQL server user information. Ask your host if you are unsure of this information.

Now that we've defined our connection information, we connect!
// connect to the mysql server
$link = mysql_connect($server, $db_user, $db_pass)
or die ("Could not connect to mysql because ".mysql_error());

// select the database
mysql_select_db($database)
or die ("Could not select database because ".mysql_error());
Here we are connecting to the MySQL server with our username and password, and then we are selecting the database we will be working with. If, for some reason, our connection attempt fails, the or die() line will kill the command, and print an error message telling us what went wrong.

If we're successful, we'll want to move on to putting data into the database.
 

about this site
site map
forums
ask a question
link this site

html tutorials
css tutorials
php tutorials
javascript tutorials
htaccess tutorials

graphics design
graphics tutorials
website design
internet copyright

about domains
about web hosting
hosting tutorial
xentrik hosting
ftp tutorials

stats logger
search engines
code generators
button labeller
remote services

font archive
website layouts
website graphics
useful scripts