Connect to Wamp Database PHP MYSQL


Connect To Database with PHP MYSQL

To connect to a mysql database,

1) Create a file such as connect.inc or connect.php.
2) Add the following code.

<?php
function public_db_connect() {
     
    $host = "localhost";  //usually always localhost
    $user = "root"; //user for wamp
    $pw = ""; //no password for wamp
    $database = "mydb"; //database name

//connect to mysql
    $db = mysql_connect($host,$user,$pw)
       or die("Cannot connect to mySQL.");
//connect to mysql database
    mysql_select_db($database,$db)
       or die("Cannot connect to database.");
  
    return $db;
 }
 ?>

3) In your file that need to connect to the database you must write the following code at the top of the page:
include('connect.inc');

Alternatively, you could use the same code on any page for which you want tom connect to the database. However, keeping include files in a safe directory is more secure than just leaving the access codes on random pages.