connect to db 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: db connection in php
Just include this Temlate in other file using PHP Include/Require Keywords
And Make Connection In One Shot :)
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test";
$con = mysqLi_connect($server, $username, $password, $database);
if(!$con){
die ("Connection Terminated! by Die() function". mysqLi_connect_error());
}
else {
echo "Connection Succefully Happened! <br>";
}
?>
Example 3: 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[];
}