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();
}
?>
Hi, this is a comment.
To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
Commenter avatars come from Gravatar.