How To Connect Database In PHP With Example

1
373
corephpconnection

Connecting to a database in PHP is a pretty straightforward process. You can connect using either PDO or MySQLi, or both.

Now that we have created our connection string, let’s create an empty database called test1 and insert some data into it using PHP code:

Using MySQLi:-

<?php
$mysqli = new mysqli(“localhost”, “root”, “test1”);
$mysqli->connect($mysqli_db_name);
if(!$mysqli){
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Database Connected successfully”;
// Insert some data into the database
// Close the connection
?>

Using PDO:-

<?php
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 “Database Connected successfully”;
} catch(PDOException $e) {
echo “Connection failed: “ . $e->getMessage();
}
?>

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here