X
HOME HTML CSS JAVASCRIPT SQL PHP JQUERY XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

PHP - Adding a Database


Learn PHP Classic by building a web site from scratch.

Part III: Adding a Database.


What We Will Do

In this chapter we will:

  • Create a page to list data from a database

Displaying Data from Database

With PHP, you can easily display data from a database.

You can connect to an existing database, or create a new database from scratch.

In this example we will connect to an existing MS Access database.

You can download the database from this link: Northwind.zip


Adding a Customers Page

In the "DemoPHP" folder, create a new PHP file named "Customers.php".

Put the following code inside the file:

Customers.php

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Site.css">
</head>
<body>
<div id="main">
<h1>Customers</h1>

<?php
//create an ADO connection and open the database
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WebData\Northwind.mdb");

//execute an SQL statement and return a recordset
$rs = $conn->execute("SELECT CompanyName, City, Country FROM Customers");
$num_columns = $rs->Fields->Count();

echo "<table border='1'>";
echo "<tr><th>Name</th><th>City</th><th>Country</th></tr>";
while (!$rs->EOF) //looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" . $rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";

//close the recordset and the database connection
$rs->Close();
$rs = null;
$conn->Close();
$conn = null;
?>

<?php include("Footer.php"); ?>

</div>
</body>
</html> 

Run example »

Creating a New Database

Download an empty database from this link: Empty Database.zip

In the "DemoPHP" folder, create a new PHP file named "CreateCustomers.php".

Put the following code inside the file:

CreateCustomers.php

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Site.css">
</head>
<body>
<div id="main">
<h1>Customers</h1>

<?php
//create an ADO connection and open the database
$conn=new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=C:\WebData\EmptyDatabase.mdb");

$conn->execute("CREATE TABLE Customers (CustomerID INT IDENTITY,CustomerName NVARCHAR(255),ContactName NVARCHAR(255),Address NVARCHAR(255),City NVARCHAR(255),PostalCode NVARCHAR(255),Country NVARCHAR(255))");
$conn->close();
$conn=null;
?>

<?php include("Footer.php"); ?>

</div>
</body>
</html> 


Congratulations

You have added a database to your web project.



Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates FREE Website Templates Free HTML Templates

SHARE THIS PAGE

facebook