phpmyadmin 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: how to connect pdo php database

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
  $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
  // set the PDO error mode to exception
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>

Example 3: mysql connection phpmyadmin

<?php
  // This is for checking if your file is linked in your page or game or whatever
  echo "IT WORKS"; // My File is successfuly Linked

  //Remember to create a Database in phpmyadmin or any Online Database
  // the values passed in this parameters are:  the host, the user, user password and the database Name
  $con = mysqli_connect('localhost', 'root', 'root', 'unityaccess');

  // check that connection happen
  if(mysqli_connect_errno()) {
    echo "1: Connection Failed"; //error code #1 = connection Failed
    exit();
  }
?>

Tags:

Sql Example