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: 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');
?>
Example 4: php mysql connect
<?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 5: 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 6: how do you connect the database
I USE JDCB
I use CONNECTION database to make connection
I create STATEMENT than I use statement to create query
And run the query and get the RESULT SET
Connection = import java.sql.Connection;
Driver manager = import java.sql.DriverManager;
Connection connection = DriverManager.getConnection(url, userName, passWord);
Connection String Syntax:
jdbc:DataBaseType"subprotocal:Host:port:SID
After succesfully created the connect next step is STATEMENT
import java.sql.Statement;
Statement statement = connection.createStatement();
-We use createStatement() method to create the statement from our connection.
-The result we get from this type of statement can only move from top to bottom,
not other way around
Once we have statement we can run the query and get the result to
ResultSet format
import java.sql.ResultSet;
We use the method executeQuery() to execute our queries
ResultSet result = statement.executeQuery("Select * from employees");