mysqli_connect()
to establish a connection.Q. program to connect database in php
<?php
// Step 1: Define database credentials
$host = “localhost”; // Server name (usually “localhost”)
$user = “root”; // Database username
$pass = “”; // Database password (leave empty for XAMPP)
$dbname = “mydatabase”; // Database name
// Step 2: Connect to the database
$conn = mysqli_connect($host, $user, $pass, $dbname);
// Step 3: Check connection status
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully!”;
// Step 4: Close the connection (optional but recommended)
mysqli_close($conn);
?>
mysqli_connect($host, $user, $pass, $dbname);
→ Establishes the connection.mysqli_connect_error();
→ Returns an error message if the connection fails.mysqli_close($conn);
→ Closes the connection when it’s no longer needed.MySQL is an open-source Relational Database Management System (RDBMS) that allows you to store, manage, and retrieve structured data efficiently. It uses SQL (Structured Query Language) for querying and managing data.
PHP provides several ways to connect to a MySQL database:
The mysqli_connect() function is used to establish a database connection.
<?php
$host = “localhost”; // Server name
$user = “root”; // Database username
$pass = “”; // Password (empty for XAMPP)
$dbname = “mydatabase”; // Database name
// Create connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully!”;
?>
<?php
$host = “localhost”;
$user = “root”;
$pass = “”;
$dbname = “mydatabase”;
// Create connection
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully!”;
?>
PHP provides several functions to interact with MySQL databases. Here are three commonly used ones:
1. mysqli_connect() – Connecting to a Database. This function is used to establish a connection between PHP and MySQL.
Example:
<?php
$conn = mysqli_connect(“localhost”, “root”, “”, “mydatabase”);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully!”;
?>
2. mysqli_query() – Executing SQL Queries. This function is used to execute SQL queries such as SELECT, INSERT, UPDATE, DELETE.
Example:
<?php
$conn = mysqli_connect(“localhost”, “root”, “”, “mydatabase”);
// Insert data into a table
$sql = “INSERT INTO users (name, email) VALUES (‘John Doe’, ‘john@example.com’)”;
if (mysqli_query($conn, $sql)) {
echo “Record inserted successfully!”;
} else {
echo “Error: ” . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>
3. mysqli_fetch_assoc() – Fetching Data as an Associative Array. This function is used to retrieve data from a result set in the form of an associative array.
Example:
<?php
$conn = mysqli_connect(“localhost”, “root”, “”, “mydatabase”);
// Fetch user data
$sql = “SELECT * FROM users”;
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo “ID: ” . $row[“id”] . ” – Name: ” . $row[“name”] . “<br>”;
}
mysqli_close($conn);
?>
<?php
// Step 1: Connect to the Database
$conn = mysqli_connect(“localhost”, “root”, “”, “mydatabase”);
// Check connection
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully!<br>”;
// Step 2: Create Table (if not exists)
$table_sql = “CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
)”;
if (mysqli_query($conn, $table_sql)) {
echo “Table ‘users’ is ready!<br>”;
} else {
echo “Error creating table: ” . mysqli_error($conn);
}
// Step 3: Insert Data into Table
$insert_sql = “INSERT INTO users (name, email) VALUES (‘John Doe’, ‘john@example.com’)”;
if (mysqli_query($conn, $insert_sql)) {
echo “Record inserted successfully!<br>”;
} else {
echo “Error inserting record: ” . mysqli_error($conn);
}
// Step 4: Retrieve and Display Data
$select_sql = “SELECT * FROM users”;
$result = mysqli_query($conn, $select_sql);
echo “<h3>User List:</h3>”;
while ($row = mysqli_fetch_assoc($result)) {
echo “ID: ” . $row[“id”] . ” – Name: ” . $row[“name”] . ” – Email: ” . $row[“email”] . “<br>”;
}
// Step 5: Close Connection
mysqli_close($conn);
?>
A session is used to store user data on the server across multiple pages. PHP assigns a unique session ID to each user.
Steps to Handle Sessions in PHP
<?php
session_start();
$_SESSION[“username”] = “Rajesh”;
echo “Session started.”;
?>
<?php
session_start();
echo “Welcome, ” . $_SESSION[“username”];
?>
<?php
session_start();
session_unset();
session_destroy();
echo “Logged out.”;
?>
Advantages of Session: Sessions are Secure, stores more data than cookies, maintains user authentication.
<?php
session_start();
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$username = $_POST[“username”];
$password = $_POST[“password”];
// Simple authentication (Replace with database in real projects)
if ($username == “admin” && $password == “1234”) {
$_SESSION[“user”] = $username;
$_SESSION[“pass”] =$password;
header(“Location: dashboard.php”); // Redirect to dashboard
exit();
} else {
echo “Invalid username or password!”;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method=”POST”>
<input type=”text” name=”username” placeholder=”Username” required><br><br>
<input type=”password” name=”password” placeholder=”Password” required><br><br>
<button type=”submit”>Login</button>
</form>
</body>
</html>
<?php
session_start();
if (!isset($_SESSION[“user”]) || !isset($_SESSION[“pass”])) {
header(“Location: index.php”); // Redirect if not logged in
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h2>Welcome, <?php echo $_SESSION[“user”]; ?>!</h2>
<h2> In this page,you can use the session variable store value here like username: <?php echo $_SESSION[‘user’].” and password:”.$_SESSION[‘pass’];?> entered from login page.</h2>
<a href=”logout.php”>Logout</a>
</body>
</html>
<?php
session_start();
session_unset();
session_destroy();
header(“Location: index.php”); // Redirect to login page
exit();
?>
<?php
// Step 1: Connect to the database
$conn = new mysqli(“localhost”, “root”, “”, “your_database”);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
// Step 2: Fetch data from Employee table
$sql = “SELECT Eid, Ename, Salary FROM Employee”;
$result = $conn->query($sql);
// Step 3: Display data in a table
echo “<table border=’1′>
<tr>
<th>Eid</th>
<th>Ename</th>
<th>Salary</th>
</tr>”;
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo “<tr>
<td>{$row[‘Eid’]}</td>
<td>{$row[‘Ename’]}</td>
<td>{$row[‘Salary’]}</td>
</tr>”;
}
} else {
echo “<tr><td colspan=’3′>No records found</td></tr>”;
}
echo “</table>”;
// Step 4: Close the connection
$conn->close();
?>