Neel koshiya j.
1.Write a PHP script to connect to a MySQL database and display a
success or failure message.
<!DOCTYPE html>
<html>
<head>
<title>Database Connection</title>
<style> body { font-
family: Arial, sans-serif;
background-color: #eef; text-
align: center; padding-top:
50px;
.message {
padding: 20px;
border-radius: 8px;
display: inline-block;
font-size: 18px;
.success { background-
color: #d4edda; color:
#155724;
.error {
background-color: #f8d7da;
color: #721c24;
}
</style>
</head>
2302020101518 1
Neel koshiya j.
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";
// Step 1: Connect to MySQL server without selecting DB
$conn = new mysqli($servername, $username, $password);
// Check connection to MySQL Server if ($conn->connect_error) { die("<div class='message
error'>Connection to MySQL failed: " . $conn->connect_error . "</div>");
// Step 2: Create database if not exists
$sql = "CREATE DATABASE IF NOT EXISTS $dbname"; if ($conn->query($sql) ===
TRUE) { echo "<div class='message success'>Database '$dbname' is
ready!</div><br>";
} else { die("<div class='message error'>Error creating database: " . $conn->error .
"</div>");
// Step 3: Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Final check if ($conn->connect_error) { die("<div class='message error'>Final connection
failed: " . $conn->connect_error . "</div>"); } else {
echo "<div class='message success'>Connected successfully to the database '$dbname'!</div>";
2302020101518 2
Neel koshiya j.
// Close connection
$conn->close();
?>
</body>
</html>
OUTPUT:
2302020101518 3
Neel koshiya j.
2 Create a table students and perform the following operations:
• Insert 5 student records
2302020101518 4
Neel koshiya j.
• Display all records
• Update the name of one student
• Delete one student based on ID
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
// Create database
$sql = "CREATE DATABASE db12";
$ans=mysqli_query($conn,$sql);
if(!$ans)
echo "<font size=+4>Error creating database: " . mysqli_error($conn);
else
2302020101518 5
Neel koshiya j.
echo "<font size=+4>Database created successfully";
mysqli_close($conn);
?>
// Step 3: Insert 5 student records (from your image)
$check = $conn->query("SELECT COUNT(*) AS total FROM students");
$count = $check->fetch_assoc();
if ($count['total'] == 0) {
$conn->query("INSERT INTO students (name, age, grade) VALUES
('Neha Patil', 20, 'A+'),
('Khyati Parmar', 19, 'B+'),
('Shubham Pandy', 20, 'C+'),
('Alok Mourya', 19, 'A+'),
('Monika Pandy', 20, 'B+')
");
// Step 4: Display all records
$result = $conn->query("SELECT * FROM students");
2302020101518 6
Neel koshiya j.
echo "<h2>📚 Student Records</h2>"; echo "<table
border='1' cellpadding='10' cellspacing='0'>"; echo "<tr
style='background-color:#f0f0f0;'>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['age']}</td>
<td>{$row['grade']}</td>
</tr>";
echo "</table>";
// Close connection
$conn->close();
?>
<?php
$conn = new mysqli("localhost", "root", "", "stu_details"); if ($conn-
>connect_error) die("Connection failed: " . $conn->connect_error);
if (isset($_GET['id'])) {
$id = $_GET['id'];
2302020101518 7
Neel koshiya j.
Update the name of one student
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
2302020101518 8
Neel koshiya j.
$age = $_POST['age'];
$grade = $_POST['grade']; $conn->query("UPDATE students SET name='$name', age='$age',
grade='$grade' WHERE id=$id"); header("Location: students.php");
exit();
// Fetch data
$result = $conn->query("SELECT * FROM students WHERE id=$id");
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
} else {
echo " Student not found.";
exit();
} else {
echo " No student ID provided.";
exit();
}
?>
• Delete one student based on ID
2302020101518 9
Neel koshiya j.
<h2> Edit Student</h2>
<form method="post">
Name: <input type="text" name="alok mourya" value="<?= $row['name'] ?>" required><br><br>
Age: <input type="number" name="21" value="<?= $row['age'] ?>" required><br><br>
Grade: <input type="text" name="A-" value="<?= $row['grade'] ?>" required><br><br>
<input type="submit" value="Update Student">
</form>
<a href="students.php">⬅️ Back to List</a>
<?php
$conn = new mysqli("localhost", "root", "", "stu_details"); if ($conn-
>connect_error) die("Connection failed: " . $conn->connect_error);
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
$conn->query("DELETE FROM students WHERE id=$id");
header("Location: students.php");
exit();
2302020101518 10
Neel koshiya j.
3. Build a simple web application that performs Create, Read, Update, and
Delete operations on a student table using AJAX for asynchronous
communication and JSON for data handling.
Connect.php:-
<?php
$server="localhost";
$username="root";
$password="";
$connect=mysqli_connect($server,$username,$password); if (!$connect) {
die("Connection fai".mysqli_connect_error());
}
$database= "CREATE DATABASE crud_json"; $ans = mysqli_query($connect , $database); if (!$ans) {
echo "Database Creating Fail".mysqli_error($connect);
} else {
echo "Database created Successfully";
mysqli_close($connect);
?>
Createtable.php:-
<?php
$server="localhost";
2302020101518 11
Neel koshiya j.
$username="root";
$password="";
$database=”crud_json”; $connect=mysqli_connect($server,$username,$password,$databa se); if
(!$connect) { die("Connection
fai".mysqli_connect_error());
$sql=”CREATE TABLE users(id int, name varchar(20), email varchar(20), phone int)”;
$query=mysqli_query($connect,$sql); if (!$query) {
echo "Table Creating Fail".mysqli_error($connect);
} else { echo "Table created
Successfully";
mysqli_close($connect);
db.php:-
<?php
$pdo = new PDO("mysql:host=localhost;dbname=crud_json",
"root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
api.php:-
<?php
include 'db.php';
$action = $_GET['action'];
if ($action == 'read') {
$stmt = $pdo->query("SELECT * FROM users"); echo
json_encode($stmt>fetchAll(PDO::FETCH_ASSOC));
2302020101518 12
Neel koshiya j.
if ($action == 'create') {
$data = json_decode(file_get_contents("php://input"));
$stmt = $pdo->prepare("INSERT INTO users (name, email, phone) VALUES (?, ?, ?)");
$stmt->execute([$data->name, $data->email, $data->phone]); echo json_encode(['status' =>
'success']);
if ($action == 'update') {
$data = json_decode(file_get_contents("php://input"));
$stmt = $pdo->prepare("UPDATE users SET name=?, email=?, phone=? WHERE id=?");
$stmt->execute([$data->name, $data->email, $data->phone,
$data->id]); echo json_encode(['status'
=> 'success']);
if ($action == 'delete') {
$data = json_decode(file_get_contents("php://input"));
$stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
$stmt->execute([$data->id]); echo json_encode(['status' => 'success']);
?>
Index.php:-
<!DOCTYPE html>
<html>
<head>
<title>PHP AJAX JSON CRUD</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
2302020101518 13
Neel koshiya j.
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstr ap.min.css" rel="stylesheet"
integrity="sha384-
SgOJa3DmI69IUzQ2PVdRZhwQ+dy64/BUtbMJw1MZ8t5HZApcHrRKUc 4W0kG879m7"
crossorigin="anonymous">
</head>
<div class="container">
<body>
<h2>User CRUD using PHP, AJAX & JSON</h2>
<form id="userForm">
<input type="hidden" id="id" class="form-control mg-3">
Name: <input type="text" id="name" class="form-control mg3"><br>
Email: <input type="text" id="email" class="form-control mg3"><br>
Phone: <input type="text" id="phone" class="form-control mg3"><br>
<button type="submit" class="btn btn-success">Save</button>
</form>
<h3>Users List</h3>
<table id="userTable" border="1" solid class="table tablestripped"></table>
<script> loadData();
function loadData() {
$.getJSON('api.php?action=read', function(data) { var rows =
'<tr><th>Name</th><th>Email</th><th>Phone</th><th>Action</th>
</tr>';
$.each(data, function(k, user) { rows += `<tr> <td>${user.name}</td>
<td>${user.email}</td>
<td>${user.phone}</td>
2302020101518 14
Neel koshiya j.
<td>
<button class="btn btn-primary" onclick='editUser(${JSON.stringify(user)})'>Edit</button>
<button class="btn btn-danger" onclick='deleteUser(${user.id})'>Delete</button> </td>
</tr>`;
});
$('#userTable').html(rows);
});
$('#userForm').submit(function(e) { e.preventDefault(); const userData = { id: $('#id').val(),
name: $('#name').val(), email: $('#email').val(), phone: $('#phone').val()
};
const action = userData.id ? 'update' : 'create';
$.ajax({ url: 'api.php?action=' + action, method: 'POST', contentType:
'application/json', data: JSON.stringify(userData), success: function() {
$('#userForm')[0].reset();
$('#id').val(''); loadData();
});
});
function editUser(user) {
$('#id').val(user.id);
$('#name').val(user.name);
$('#email').val(user.email);
$('#phone').val(user.phone);
function deleteUser(id) { if (confirm("Are you sure?")) {
$.ajax({ url: 'api.php?action=delete', method: 'POST', contentType: 'application/json',
data: JSON.stringify({ id }), success: function() { loadData();
2302020101518 15
Neel koshiya j.
});
</script>
</div>
</body>
</html>
2302020101518 16