Create a Mysql Database Connection Using PDO

Example: Create a MySql Connection using PDO (PHP Data Object)

<?php
	// Creating MySql PDO Connection 
	$servername = "localhost";
	$username = "username";
	$dbname = "databasename";
	$password = "password";

	try {
		$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
		// set the PDO error mode to exception
		$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		echo "Connected successfully"; 
    }
	catch(PDOException $e) {
	    // error handling
		echo "Connection failed: " . $e->getMessage();
    }
?>

Example: Closing PDO Connection

<?php
	// Closing MySql PDO Connection 
	$conn = null;
?>

One thought on “Create a Mysql Database Connection Using PDO

  • AffiliateLabz
    February 16, 2020 at 1:18 am

    Great content! Super high-quality! Keep it up! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>