Thursday, July 17, 2008

PHP (2) - MySQL Database

PHP/MYSQL TUTORIAL/PROGRESS BLOG


Comments/Guest Book


Xampp phpMyAdmin
One thing I like about XAmpp is the built version of phpMyAdmin, which is an easy to use front end for MySQL. This can be accessed by going to "http://localhost/xampp" and following the link to phpMyAdmin under the tools section of the left hand navigation, on the XAmpp front page (http://localhost/phpMyAdmin).

CREATING A NEW DATABASE
A new database can be created easily using the Create new database field:


CHOOSING TABLE NAME AND NUMBER OF FIELDS
I have named my database "test1", on the next page choosing "example1" as the new table on the database. I chose five for the Number of fields (different bits of information that will be entered into the table). When creating a database it is best to plan what information is going to be entered into the table and entering the Number of fields accordingly. Both the database and table name should be relevant to what it is going to be used for so you can remember what is what when you have multiple databases and tables.

FIELD NAMES, TYPES AND LENGTHS

For this Database table I chosen field names which would be used on a comments page or guest book; Name, Subject, Comment and URL, as well as ID which will be the comments number (1 for the first comment, 2 for the second, etc). I have set the field type for ID to INT, with the others as VARCHAR. For the Length/Values, I have chosen numbers which I think will be about right for these field inputs.

I have also chosen for the ID field to be set to 'Primary' and 'auto-increment', which makes it the primary field as well as automatically increasing the number in the field as required for the ID field. Choose the Collation you want (chosing none defaulted to latin1_swedish_ci for me, so I chose to use ucs2_bin).



CONNECT TO DATABASE WITH PHP
Now to the coding. Bring up your text editor and enter the following:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');

$dbname = 'test1';
mysql_select_db($dbname);
?>
Things you may have changed which may be causing you problems: If you have set up a username and password for your database, change these accordingly under "$dbuser = " and "$dbpass = ". Also, if you didn't call your database "test1" then type whatever you did call it under "$dbname = ". Also ensure there are ";"'s at the end of every line where it is needed.

Save this file as a php file (I named mine connectphp.php) in C:\xampp\apache\htdocs (or the relative location if you put it somewhere else). Access the page in your web browser (http:\\localhost\connectphp.php in my case) and it should be blank, which is a good sign that it hasn't caused an error.


Information/help from:

Collin Jensen
php.net
php mysql tutorial



©Chris Guiblin 2008
URL: www.guiblin.com/chris/
EMAIL: chris@guiblin.com

No comments: