To insert data in student table using PHP
<?php
// Database connection parameters
$server = "localhost";
$username = "root";
$password = " ";
$db = "testdb";
// Create a connection to the database
$conn = mysqli_connect($server, $username, $password, $db);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
// Sample data to be inserted
$name = "Ramesh";
$rollno = "34";
$age = 20;
// SQL query to insert data into the 'student' table
$sql = "INSERT INTO student (name, rollno, age) VALUES ('$name', '$rollno', $age)";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
// Close the database connection
$conn->close();
?>
To create database db using PHP
<?php
// Database connection parameters
$server = "localhost";
$username = "root";
$password = " ";
$db = "testdb";
// Create a connection to the database
$conn = mysqli_connect($server, $username, $password);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
// Database name to be created
$databaseName = "db";
// SQL query to create the database
$sql = "CREATE DATABASE IF NOT EXISTS $databaseName";
// Execute the query
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
// Close the MySQL connection
$conn->close();
?>
To create and print session variables (session1.php)
<?php
// Start a session
session_start();
// Set session variables
$_SESSION['username'] = 'john_doe';
$_SESSION['user_role'] = 'admin';
echo 'Session started and variables set.';
?>
<?php
(session2.php)
// Start the session
session_start();
// Check if the session variables are set
if (isset($_SESSION['username']) && isset($_SESSION['user_role'])) {
// Display session variables
echo 'Username: ' . $_SESSION['username'] . '<br>';
echo 'User Role: ' . $_SESSION['user_role'];
} else {
echo 'Session variables not set.';
?>