how to connect database to php code example
Example 1: php sql connection
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn= mysqli_connect($servername,$username,$password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected Successfully.";
?>
Example 2: 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 3: how to connect to a database in php
<?php
$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";
?>
Example 4: php mysql connect
$host = 'localhost';
$user = 'root';
$pw = '';
$dbname = 'database';
$dsn = "mysql:host=$host;dbname=$dbname";
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'];
$db = new PDO($dsn, $user, $pw, $options);
$db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$qry = 'select * from table;';
$result = $db -> query($qry);
while ($row = $result -> fetch()) {
$id = $row[];
}