php to mysql connect to database code example
Example 1: php connect to mysql
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
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');
?>