create mysql connection in php code example

Example 1: php sql connection

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

// Create connection
$conn= mysqli_connect($servername,$username,$password,$dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected Successfully.";
?>

Example 2: php mysql pdo connection

<?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: 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 4: php mysql connect

$host = 'localhost'; // URL to the server
$user = 'root'; // Username (xampp = root)
$pw = ''; // Password (xampp = )
$dbname = 'database'; // The name of your database 
$dsn = "mysql:host=$host;dbname=$dbname";
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']; // If you want to use utf-8 use this line

$db = new PDO($dsn, $user, $pw, $options); // Database Object
$db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // Use this if you want an associate array
// $db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); Use this if you want an indexed array

$qry = 'select * from table;'; // Your query
$result = $db -> query($qry); // execute query

while ($row = $result -> fetch()) {
    $id = $row[/*column-name*/];
}

Tags:

Php Example