How to Connect PHP with MySQL Database
Code for MySQL connection with PHP
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php define('DB_SERVER','localhost'); define('DB_USER','root'); define('DB_PASS' ,''); define('DB_NAME', 'dbname'); $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?> |
1. In the below we can define our hostname. For local, you can use localhost. If you want to access the other host then put that host name or Server IP here
1 |
define('DB_SERVER','localhost'); |
2.This code for db user name. For local we use root. But you can create db user name whatever you want.
1 |
define('DB_USER','root'); |
3. Here we can define db password. For local you should leave blank.
1 |
define('DB_PASS' ,''); |
4.Here we define our database name
1 |
define('DB_NAME', 'dbname'); |
5. The mysqli_connect() function opens a new connection to the MySQL server.
1 |
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME); |