First things First; Connecting to the Database
Ok, now we have written out the rough plan, I need to start learning PHP in order to carry it out. The first thing I intend to do to practice is to create a form with a text input to get data into the database and another page to display that data.
The first thing I did was to create a database in phpmyadmin called test, with a table called form_test with two fields in that; id, and text. The id will auto increment with each new value and the text field is just that - a free text field. SQL to create this is:
CREATE TABLE form_test ( id int(11) NOT NULL auto_increment, `text` text collate latin1_general_ci NOT NULL, PRIMARY KEY (id) )
So now we have a database to play with, how do I connect to it using php?? Following the instructions at php mysql tutorial I created a file called db_config.php as follows:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'test';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
?>
Going through the above,
- $dbhost - this is where your database is stored. Some hosting companies will either give you the ip address of the database, or it could just simply be ‘localhost’ as it is with mine (I’m doing this on my local machine).
- $dbuser - the username of the database. When using on a live site, never use the username of ‘root’ as this has full privelages, create a new username.
- $dbpass - the password for your chosen username
- $dbname - the name of the database you created.
Now I have the database connection all set up and raring to go, I want to see if I can create a query to put some data into the table. I created a blank HTML page, included the above file in the first line, and then wrote an INSET query…
<?php
include 'db_config.php';
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
PHP Form Test
</title>
<link rel="stylesheet" type="text/css" href="styles/screen.css">
</head>
<body>
<h1>Hello World!!</h1>
<?php
mysql_query ("INSERT INTO form_test (text) VALUES ('If this works this will be the first entry into the database!!')");
?>
</body>
</html>
I had no idea if this was going to work as I’ve never written a page that connects to a database before! So here goes…
It worked!! The image on the left is a screen grab of phpMyAdmin before I ran the above page, and the image on the left is after.
Fine, so thats great but it’s all well and good having the data being entered into the database from within the php code itself, but it’s not exactly the ideal solution to a CMS - we’re going to need a form to enter the data into the database. For now, I’ll leave that until the next post…
No comments yet.

