It’s very easy to connect to MySQL database using PHP. You just need to know HOSTNAME, USERNAME (this is DB username), PASSWORD (pw for DB), DB_NAME and that’s it.
It’s better to have a separate PHP file named connect.php for connection information.
There are TWO ways of doing this. EXAMPLE 1 is more cleaner and my preferred way of doing it; but EXAMPLE 2 can also be used for smaller and more simple projects.
EXAMPLE 1
filename: connect.php
<?php
define('HOSTNAME', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', ''); //it's usually empty for MySQL
define('DB_NAME', 'crud-app'); //create DB in MySQL and define it here
$conn = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DB_NAME);
if ($conn) {
echo 'SUCCESS!';
} else {
die ('No connection!!!');
}
EXAMPLE 2
filename: connect.php
<?php
$conn = mysqli_connect('localhost', 'root', '', 'crud-app');
if ($conn) {
echo 'SUCCESS!';
} else {
die ('No connection!!!');
}