parajulirajesh.com.np

Database connection in PHP

<?php
$servername = “localhost”;
$username = “root”;
$password = “”;
$dbname = “my_database”;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}

echo “Connected successfully”;

// Close connection
mysqli_close($conn);
?>

Create connection with database and create database in php

<?php
$servername = “localhost”;
$username = “root”;
$password = “”;

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}

// SQL query to create database
$sql = “CREATE DATABASE IF NOT EXISTS my_database”;

// Execute query
if (mysqli_query($conn, $sql)) {
echo “Database created successfully”;
} else {
echo “Error creating database: ” . mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>

Q. Create database and  table and insert data in that table in php 

<?php
/* ———- 1. Connection ———- */
$host = “localhost”;
$user = “root”;
$pass = “”;
$db = “my_database”;
$table = “students”;

$conn = mysqli_connect($host, $user, $pass);

if (!$conn) {
die(“Connection failed”);
}
echo “Connected successfully<br>”;

/* ———- 2. Create Database ———- */
$create_db = “CREATE DATABASE IF NOT EXISTS $db”;
mysqli_query($conn, $create_db);
echo “Database created<br>”;

/* ———- 3. Select Database ———- */
mysqli_select_db($conn, $db);
echo “Database selected<br>”;

/* ———- 4. Create Table ———- */
$create_table = “CREATE TABLE IF NOT EXISTS $table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50)
)”;
mysqli_query($conn, $create_table);
echo “Table created<br>”;

/* ———- 5. Insert Data ———- */
$name = “John”;
$email = “john@gmail.com”;

$insert = “INSERT INTO $table (name, email) VALUES (‘$name’, ‘$email’)”;
mysqli_query($conn, $insert);
echo “Data inserted successfully<br>”;

/* ———- Close Connection ———- */
mysqli_close($conn);
?>

 

Database data fetching usig mysqli_fetch_array().

<?php
// 1️⃣ Connect to MySQL
$conn = mysqli_connect(“localhost”, “root”, “”);
if (!$conn) die(“Connection failed: ” . mysqli_connect_error());

// 2️⃣ Create Database
mysqli_query($conn, “CREATE DATABASE IF NOT EXISTS student_db”);
mysqli_select_db($conn, “student_db”);

// 3️⃣ Create Table
mysqli_query($conn, “CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
)”);

// 4️⃣ Insert Record
mysqli_query($conn, “INSERT INTO students (name, email, age)
VALUES (‘Sita’, ‘sita@gmail.com’, 21)”);

// 5️⃣ Fetch & Display Records
$result = mysqli_query($conn, “SELECT * FROM students”);

echo “<h3>Student List</h3>”;
echo “<table border=’1′ cellpadding=’10’>
<tr><th>ID</th><th>Name</th><th>Email</th><th>Age</th></tr>”;

while ($row = mysqli_fetch_array($result)) {
echo “<tr>
<td>{$row[‘id’]}</td>
<td>{$row[‘name’]}</td>
<td>{$row[’email’]}</td>
<td>{$row[‘age’]}</td>
</tr>”;
}

echo “</table>”;

mysqli_close($conn);
?>

Fetch data from database using mysqli_fetch_assoc()

<?php
// Connect to MySQL
$conn = mysqli_connect(“localhost”, “root”, “”);
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}

// Create Database if it doesn’t exist
if (!mysqli_query($conn, “CREATE DATABASE IF NOT EXISTS student_db”)) {
die(“Database creation failed: ” . mysqli_error($conn));
}

// Select the database
mysqli_select_db($conn, “student_db”);

// Create Table if it doesn’t exist
$tableQuery = “CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
)”;
if (!mysqli_query($conn, $tableQuery)) {
die(“Table creation failed: ” . mysqli_error($conn));
}

// Insert Data (avoid duplicates)
$checkQuery = “SELECT * FROM students WHERE email=’sita@gmail.com'”;
$checkResult = mysqli_query($conn, $checkQuery);

if (mysqli_num_rows($checkResult) == 0) {
$insertQuery = “INSERT INTO students (name, email, age)
VALUES (‘Sita’, ‘sita@gmail.com’, 21)”;
if (!mysqli_query($conn, $insertQuery)) {
die(“Data insertion failed: ” . mysqli_error($conn));
}
}

// Fetch & Display
$result = mysqli_query($conn, “SELECT * FROM students”);

echo “<h3>Student List</h3>”;
echo “<table border=’1′ cellpadding=’10’>”;
echo “<tr><th>ID</th><th>Name</th><th>Email</th><th>Age</th></tr>”;

while ($row = mysqli_fetch_assoc($result)) {
echo “<tr>
<td>{$row[‘id’]}</td>
<td>{$row[‘name’]}</td>
<td>{$row[’email’]}</td>
<td>{$row[‘age’]}</td>
</tr>”;
}

echo “</table>”;

// Close connection
mysqli_close($conn);
?>

Practice to use mysqli_fetch_array()

<?php
$sn = “localhost”;
$un = “root”;
$ps = “”;

// Connect to MySQL server
$conn = mysqli_connect($sn, $un, $ps);

if (!$conn) {
die(“Failed connection: ” . mysqli_connect_error());
} else {
echo “Connected successfully<br>”;
}

// Create database if not exists
$dbcreate = “CREATE DATABASE IF NOT EXISTS rajesh”;

if (mysqli_query($conn, $dbcreate)) {
echo “Database created successfully<br>”;
} else {
echo “Failed to create database: ” . mysqli_error($conn);
}

// Select the database
mysqli_select_db($conn, “rajesh”);

// Create table if not exists
$dbtable = “CREATE TABLE IF NOT EXISTS teacher(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
)”;

if (mysqli_query($conn, $dbtable)) {
echo “Table created successfully<br>”;
} else {
echo “Failed to create table: ” . mysqli_error($conn);
}

// Insert data (avoid duplicates)
$checkQuery = “SELECT * FROM teacher WHERE name=’rajesh'”;
$checkResult = mysqli_query($conn, $checkQuery);

if (mysqli_num_rows($checkResult) == 0) {
$dbinsert = “INSERT INTO teacher (name) VALUES (‘rajesh’)”;
if (mysqli_query($conn, $dbinsert)) {
echo “Data inserted successfully<br>”;
} else {
echo “Failed to insert data: ” . mysqli_error($conn);
}
}

// Select data
$selectdata = “SELECT * FROM teacher”;
$display = mysqli_query($conn, $selectdata);

echo “<h2>Teacher Info</h2>”;

// Display each record line by line
while ($row = mysqli_fetch_assoc($display)) {
echo “ID: {$row[‘id’]} | Name: {$row[‘name’]}<br>”;
}

// Close connection
mysqli_close($conn);
?>

Practice mysqli_fetch_assoc()

<?php
// Connect to MySQL
$conn = mysqli_connect(“localhost”, “root”, “”);
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}

// Create Database if it doesn’t exist
if (!mysqli_query($conn, “CREATE DATABASE IF NOT EXISTS student_db”)) {
die(“Database creation failed: ” . mysqli_error($conn));
}

// Select the database
mysqli_select_db($conn, “student_db”);

// Create Table if it doesn’t exist
$tableQuery = “CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
age INT
)”;
if (!mysqli_query($conn, $tableQuery)) {
die(“Table creation failed: ” . mysqli_error($conn));
}

// Insert Data (avoid duplicates)
$checkQuery = “SELECT * FROM students WHERE email=’sita@gmail.com'”;
$checkResult = mysqli_query($conn, $checkQuery);

if (mysqli_num_rows($checkResult) == 0) {
$insertQuery = “INSERT INTO students (name, email, age)
VALUES (‘Sita’, ‘sita@gmail.com’, 21)”;
if (!mysqli_query($conn, $insertQuery)) {
die(“Data insertion failed: ” . mysqli_error($conn));
}
}

// Fetch & Display
$result = mysqli_query($conn, “SELECT * FROM students”);

echo “<h3>Student List</h3>”;

// Display each student record line by line
while ($row = mysqli_fetch_assoc($result)) {
echo “ID: {$row[‘id’]} | Name: {$row[‘name’]} | Email: {$row[’email’]} | Age: {$row[‘age’]}<br>”;
}

// Close connection
mysqli_close($conn);
?>

Difference Between mysqli_fetch_array() and mysqli_fetch_assoc().

Basismysqli_fetch_array()mysqli_fetch_assoc()
Return TypeReturns both numeric index + associative index by defaultReturns only associative index
Index Access$row[0] and $row['name'] both workOnly $row['name'] works
Memory UsageUses more memory (stores data twice)Uses less memory
SpeedSlightly slowerSlightly faster
FlexibilityMore flexible (can access both ways)Simpler and cleaner
Example$row = mysqli_fetch_array($result);$row = mysqli_fetch_assoc($result);

IP Address in Networking

An IP (Internet Protocol) address is a unique numerical label assigned to each device connected to a network that uses the Internet Protocol for communication. It identifies and locates devices so data can be sent and received correctly over networks like the internet.

Functions of an IP Address

  1. Device Identification – Identifies a device on a network.
  2. Location Addressing – Indicates where the device is located in the network.
  3. Routing – Enables routers to forward data packets to the correct destination.
  4. Network Communication – Allows devices to communicate over local and global networks.

Difference Between IPV4 and IPV6

IPv4IPv6
32-bit address128-bit address
Written in dotted decimal format (e.g., 192.168.1.1)Written in hexadecimal format (e.g., 2001:db8::1)
About 4.3 billion addressesAlmost unlimited addresses (3.4 × 10³⁸)
Uses decimal numbersUses hexadecimal numbers
Has broadcast supportNo broadcast; uses multicast
Security is optional (IPSec optional)Built-in security (IPSec mandatory support)
Uses NAT (Network Address Translation) commonlyNAT is not required
Slower and less efficientFaster and more efficient routing

Types of IP Addresses

1. Based on Version

(A) IPv4 (Internet Protocol Version 4)

  • 32-bit address
  • Written in dotted decimal format (e.g., 192.168.1.1)
  • About 4.3 billion possible addresses
  • Example: 192.168.0.1

(B) IPv6 (Internet Protocol Version 6)

  • 128-bit address
  • Written in hexadecimal format (e.g., 2001:0db8:85a3::8a2e:0370:7334)
  • Almost unlimited number of addresses
  • Example: 2001:db8::1

2. Based on Accessibility

  • Public IP Address – Accessible over the internet.
  • Private IP Address – Used within local networks.
  • Static IP Address – Manually assigned and does not change.
  • Dynamic IP Address – Automatically assigned and may change periodically.

Classes of IPv4 Addresses (with Ranges)

IPv4 addresses are divided into five main classes:

ClassRangeDefault Subnet MaskUsage
Class A1.0.0.0 – 126.255.255.255255.0.0.0Large networks
Class B128.0.0.0 – 191.255.255.255255.255.0.0Medium networks
Class C192.0.0.0 – 223.255.255.255255.255.255.0Small networks
Class D224.0.0.0 – 239.255.255.255Not definedMulticasting
Class E240.0.0.0 – 255.255.255.255Not definedExperimental
Scroll to Top

Rajesh Parajuli

BICTE GMC

LEC.RAJESH PARAJULI

Address: Ghodaghodi Municipality-1 Sukhad kailali

Contact: 9847546279

Ghodaghodi Multiple Campus BICTE