PHP MYSQL DATABASE CONNECTION TUTORIAL

PHP MYSQL DB CONNECTION

PHP 5 and later can work with a MySQL database using: MySQLi extension … You only have to change the connection string and a few queries. With MySQLi …

Create Database connection

$db_host = “localhost” ;
$db_user = “admin” ;
$db_pass = ” ” ;
$dbcon = new mysqli ( $dhost, $dbuser, $dbpass) ;
if($dbcon->connect_errno)
{
die(“Connection Error : “.$db->connect_error);
}
else{
echo “Connection Successfully Established”;
}

Create DataBase Using Query

$Create_DB = “CREATE DATABASE IF NOT EXISTS DB_User”;
if($dbcon -> query($Create_DB) == TRUE)
{
echo “DataBase named DB_User Created Successfully”;
}
else{
echo “Error :”.$db->error;
}

Create DataBase Table using Query

$sql = “CREATE TABLE Login (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)”;
if ($dbcon->query($sql) === TRUE) {
echo “Table Login created successfully”;}
else {
echo “Error creating table: ” . $db->error;
}


Insert Data into Database Table Login

$sql = “INSERT INTO Login(firstname, lastname, email) value (‘webpage’, ‘hub’, ‘webpagehub.com@gmail.com’)”;
if($db->query($sql)==TRUE)
{
echo “Data Insertion is successfully done”;
}
else{
echo “error in insertion”.$db->error;
}

Fetch Data From Database Table Login

$sql =”SELECT * FROM Login”;
$result = $dbcon->query($sql);

if ($result->num_rows > 0) {

// output data of each row
while($row = $result->fetch_assoc())
{
$first_name = $row[‘firstname’];
$last_name = $row[‘lastname’];
$email = $row[’email’];

echo “first name : “.$first_name;
echo “last name : “.$last_name;
echo “email : “.$email;
}

}else
{
echo “No data”;
}