use php to connect to mysql database code example

Example 1: php connect to mysql

$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";


Simplified

$conn = mysqli_connect('localhost', 'username', 'password');
$database = mysqli_select_db($conn, 'database');

Example 2: mysql connect php

# MySql improved
<?php
    $mysqli = new mysqli("localhost", "username", "password", "dbname");
	$result = $mysqli->query("SELECT lastname FROM employees");
?>
# Connection with PDO
<?php
    $myPDO = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
	$result = $myPDO->query("SELECT lastname FROM employees");
?>
# With PHP legacy functions:
<?php
    mysql_connect('localhost','username','password');
    mysql_select_db("dbname");
	$result = mysql_query('SELECT lastname FROM employees');
?>

Tags:

Php Example