Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this blog, we will discuss (How to Connect to MySQL Database Using PHP)
we will create a connection with MySql DB using 2 methods.
PHP provides mysqli_connect() function to open a database connection. This function takes parameters and returns a MySQL link identifier on success or false on failure.
<?php
$dbservername="localhost";
$dbuser="root";
$dbpassword="";
$dbname="myblog";
$connection=mysqli_connect($dbservername,$dbuser,$dbpassword,$dbname);
if(! $connection ) {
die('Could not connect:Error ' . mysql_error());
}
echo 'Connected successfully:Success';
mysql_close($connection);
?>
PDO refers to PHP Data Object, which is a PHP extension that defines a lightweight and consistent interface for accessing a database in PHP. It is a set of PHP extensions that provide a core PDO
class and database-specific driver.
PDO – PDO represents a connection between PHP and the database.
PDOStatement – PDOStatement represent the prepared statement and after the execution of the statement,
sets an associated result.
PDOException – PDOException represents errors raised by PDO.
<?php
$dbuser = "root";
$dbpass = "pass"; //If your Db have a Password
try{
$dbPDO = new PDO('mysql:host=localhost;dbname=hotelDB', $dbuser, $dbpass);
$dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
echo "Database connected successfully";
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
//On successful connection.
$SuccessResult = "Secure Database Connection established.";
?>
In this blog, we learned How to Connect to MySQL Database Using PHP, you can connect your database using many ways.
How to copy input value to another form through jquery, Easy Form Validation With jQuery