Create a database connection PDO PHP

This is a simple PDO PHP database connection between your website and your database. Once you have created a database you can use this small block of code to easily connect to it and start pulling data out, edit data, add data and delete data.

This site is connected to a database in phpMyAdmin. Remeber to include your connection script in any page that requires access to your database. For simplicity I include the connection script in my header as the header is included in all front end pages.

Crate a file and name it db-connect.php or connect.php. I have this saved as connect.php and it's located in my includes folder in the websites folder structure.

                
                    $host = "localhost";
                    $database = "DB_NAME"; 
                    $username = "USERNAME"; //most likely root
                    $password = "PASSWORD"; //if required

                    try 
                        {
                            $db = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
                            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                            //Uncomment this echo to test connection - once connection is confirmed comment it out again so it does not show on all pages.
                            //echo "This site is connected to the CoderCasts database";
                        } 

                    catch (PDOException $e) 
                        {
                            echo "Could not connect to database";
                            print "Error!: " . $e->getMessage() . "";
                            die();
                        }
                
            
This site is connected to the CoderCasts database