connect PHP with database

<!DOCTYPE html>
<html lang=”en-US”>
<meta charset=”UTF-8″>
<style type = “text/css”>
table, th, td {border: 1px solid black};

$connect=new PDO(‘mysql:hostname=localhost;dbname=learn’,”root”);
print “<table> \n”;
print “<tr> \n”;
foreach ($row as $field=>$value){
print “<th> $field </th> \n”;
print “</tr> \n”;
foreach($data as $row){
print “<tr> \n”;
foreach($row as $name=>$value){
print “<td> $value </td> \n”;
print “</tr> \n”;
print “</table> \n”;
catch(PDOException $e) {
echo ‘ERROR: ‘ . $e->getMessage();

With PDO, the connection is an instance of the PDO object. When you make a PDO object, you’re making a connection to the database. The data connection command is chock-full of details:
$con = new PDO(‘mysql:host=localhost;dbname=dbname’, “username”, “password”);

Because PDO is object-oriented, use the new keyword to call the PDO
object constructor.

$connect = new PDO(‘mysql:host=localhost;dbname=dbname’, “username”,

1. Turn on error-tracking.
PDO has some features for tracking errors. These are especially useful
because the ordinary PHP error codes don’t help with PHP problems.
Turn on the PDO error-reporting mechanism with the setAttribute()
method of the PDO object.

2. Execute a query.
The PDO object’s query() method allows you to apply a query to the
database and returns the result in a special variable.
$result = $connect->query(‘SELECT * FROM contact’);

3. Set the fetch mode.
You can tell PDO to return data in a number of formats. For now, choose
FETCH_ASSOC. This format returns each record as an associative array.
This is the easiest fetch mode to work with. (You can also return each
record as a numerically indexed array, both numeric and associative
arrays, and as a special object.)
4. Read the data a row at a time.
The results of a data query are typically a table, so read the table
one row (record) at a time. The $result variable is an ordinary
array, so you can easily use a foreach loop to separate the data into
foreach($result as $row);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s