connect PHP with database

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

try{
$connect=new PDO(‘mysql:hostname=localhost;dbname=learn’,”root”);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$query=’SELECT * FROM CONTACT’;
print “<table> \n”;
$field=$connect->query($query);
$row=$field->fetch(PDO::FETCH_ASSOC);
print “<tr> \n”;
foreach ($row as $field=>$value){
print “<th> $field </th> \n”;
}
print “</tr> \n”;
$data=$connect->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
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();
}
?>
</body>
</html>

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”,
“password”);

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.
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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.)
$result->setFetchMode(PDO::FETCH_ASSOC);
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
rows.
foreach($result as $row);

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s