How do I connect to MySQL from within PHP?

If you want to connect to your database from PHP you can create a file called "db.php" in your file manager. This can be done in the following way: Where can I find on which server my MYSQL databases are running?

Then you can add the following piece of code to your db.php file. The green parts should still be adapted to your own database data.


<?php
$servername = "YourDbHost";
$username = "DbUserName";
$password = "DbPassword";

$conn = mysqli_connect($servername, $username, $password);

if (!$conn) {
which("Connection failed: " . mysqli_connect_error()); }echo

"Connected successfully";?>



It is also possible to do this via PDO, for this you can use the piece of code below. Also here you need to change the green pieces to your own data.

<php$servername
= "
YourDbHost";
$username = "
DbUsername";
$password = "
DbPassword";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); $conn->setAttribute

(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "
Connected successfully"; } catch(PDOException
$e) { echo "Connection
failed: " . $e->getMessage(); }?>






Then if your connection is successful you will see the following on your website.

How do I connect to MySQL from within PHP?