Database connection in PHP

Hi all todays programing tip is about DATABASES.
To create a connection to a database is very simple.

one way i like to do it is create a database connection file. i usually call it db_conn.php

In this db_conn file i keep all my connection settings.

the file contains the following:

<?php
$dbtype = ‘mysql’;
$dbhost = ‘serverIP/serverURL’;
$dbusername = ‘testUSER’;
$dbpasswd = ‘testPW’;
$database_name = ‘testDB’;


$connection = mysql_pconnect(“$dbhost”,”$dbusername”,”$dbpasswd”)
or die (“Couldn’t connect to server.”);
$db = mysql_select_db(“$database_name”, $connection)
or die(“Couldn’t select database.”);
?>

When you want to connect to you database there is a few things you must do.

1. The page that receives the data must be PHP
2. At the top of the page you must add the db_conn file.

<?php

require(“db_conn.php”);

?>

3. When every you want to connect to the db just use this.

<?php

$query = “Insert into post (field1, field2, field3,) values (‘” .$value1.”‘,'” .$value2.”‘,'” .$value3.”‘);”;

//echo $query; //This echo’s your query in your browser so you can view it

$res = mysql_query($query);//This runs the Query

?>

And that is all you need to do

Leave a Reply