ACCESSING A DATABASE USING PHP


Use the following variables:-

$host  - address of the host having the MySQL database.
$database - name of the database at the host.
$username - the user of the database.
$password - the password to access the database.

The variables and their values should be in a file at a secure location on the server.

dbinfo.php - example of a name of a file used to hold the database variables and 
their data.

Include the filename of the database variables once as an include file at the 
top of the program. For example:-

include("dbinfo.php");

In the database program try and access the database using an Exception procedure 
with the following variables:-

$db - results of database access.
$e - error message if there is an exception.

Note the inverted commas in the example below enclose mysql and dbname and their values.

try{
   $db = new PDO("mysql:host=$host; dbname=$database", $username, $password);
}

catch(PDOException $e){
echo "Error connecting to database ".$database."!",$e->getMessage();
exit();
}

After successfully accessing the database a copy of the database should be in the 
variable $db.

Use the following variables to select the information required from a table in the 
database:-

$tablename - name of table
$row - name of array to hold data required obtained from a row in the database.

The following code can be used to list the contents of the database to the screen.

foreach($db->query("SELECT * FROM $tablename") as $row){

   echo ("Subject: ".$row["subject"]."   Answer: ".$row["message"]);
   
}

To add an entry or request an existing one to be altered, please fill in the comments form

Home Page