Create MySQL Database With PHP

Create a dynamic web site by using MySQL Database and PHP. It is easy and I provided the code to cut and paste.

Now let get started with PHP and MySQL code for building a Dynamic Web Site:

PHP & database connection code in a lib file for inclusion

1) First we make a php file called “lib.php”
2) Then we add the following php code to the lib.php file for making a connection to the database. Be sure to change the names to match your host name, user name, password and database name :

$dbhost = ‘localhost’;
$dbuser = ‘myusername’; // you must set user name!
$dbpass = ‘mypassword’; // you must set pass word!
$dbname = ‘car_database’; // you must set database or fill-in database name in the form!

function dbconnect()
global $dbhost, $dbuser, $dbpass, $dbname;
mysql_pconnect($dbhost, $dbuser, $dbpass);
@mysql_select_db($dbname) or die (“Unable to select database”);

function query_db($query)
return @mysql_query($query);

Database Manager (PhpMyAdmin) to create a new table

3) Open up your database manager (PhpMyAdmin) and select your database, then click the SQL tab or icon for running a SQL query and copy and paste the following code in the text field then click the “Go” or “Submit” button to create the car_table database.

CREATE TABLE car_table (

car_make varchar(250) default NULL,
car_model varchar(250) default NULL,
car_year varchar(250) default NULL,
id_field int(11) NOT NULL auto_increment,
PRIMARY KEY (id_field)

PHP code for managing your table fields

4) Download Code file “cars.txt” here: Tutorials/cars.txt

5) Rename that file to “cars.php”. Notice that the first line of code is there to imports your first file “lib.php”. Why? Because for every php file that query’s the database will need to make a database connection. So why not use one file to make that connection for all php files.

6) Uploads both the “lib.php” and the “cars.php” to your web server. Make sure both files are in side of the same directory.

Third PHP file for visitors without the edit or delete functions.

7) After adding content to your database, you may want to make a third file called “viewcars.php” for the users to view the database list of cars. Do this by duplicating the “cars.php” file. But be sure to delete all of the links labeled “delete”, “edit” and “add” and remove all php blocks of code that start with “$query=INSERT INTO…, $query=UPDATE…, and $query=DELETE FROM…” to provent visitors from editing your database content.

You may also like...

Leave a Reply