3. Connect the view to the database
Now, to connect our view to the database, we have to configure a php command with our username, password, the host where the database can be found and the name of the database. Much like the head.php and foot.php we will create a new file called connect.php so that we can make our connection easily available to any page that needs to interact with the database.
Create the file: connect.php. Paste in the following code:
<?php $username = 'root'; $password = ''; $dbname = 'contact_manager'; try { $connection = new PDO('mysql:host=localhost;dbname='.$dbname.';',$username,$password); $connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch (PDOException $e) { print "Connection error " . $e->getMessage() . "<br/>"; die(); } ?>
And then, we include connect.php into our index.php by adding this line above the line: include(‘head.php’);
include('connect.php');
Visit the following url to see the page in action: http://localhost/contact_manager/
If there is no error message, it means your connection was successful. If you do see an error message, double check that you entered the correct details and make sure you are using the correct credentials.