পিএইচপি প্রোজেক্ট টিউটোরিয়াল -১

PHP MySQL INSERT Form – Student Registration

এই ফর্মটি ব্যবহার করে আপনি নতুন ছাত্রের তথ্য MySQL ডাটাবেজে ইনসার্ট করতে পারবেন।

HTML ফর্ম কোড:

<form action="" method="POST">
  <label> Name:</label><br>
  <input type="text" name="name" required><br>

  <label> Email:</label><br>
  <input type="email" name="email" required><br>

  <label> Course:</label><br>
  <input type="text" name="course" required><br>

  <input type="submit" name="submit" value="Submit">
</form>

PHP কোড (Insert Logic):

<?php
if (isset($_POST['submit'])) {
  $conn = new mysqli("localhost", "root", "", "testdb");

  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }

  $name = $_POST['name'];
  $email = $_POST['email'];
  $course = $_POST['course'];

  $sql = "INSERT INTO students (name, email, course) 
          VALUES ('$name', '$email', '$course')";

  if ($conn->query($sql) === TRUE) {
    echo "<p style='color:green; font-weight:bold;'>✅ Student registered successfully!</p>";
  } else {
    echo "<p style='color:red;'>❌ Error: " . $conn->error . "</p>";
  }

  // Show the newly inserted row
  $result = $conn->query("SELECT * FROM students ORDER BY id DESC LIMIT 1");

  if ($result->num_rows > 0) {
    echo "<table style='border-collapse:collapse; width:100%; margin-top:15px;'>
            <tr style='background:#2ecc71; color:#fff;'>
              <th style='padding:8px; border:1px solid #ccc;'>ID</th>
              <th style='padding:8px; border:1px solid #ccc;'>Name</th>
              <th style='padding:8px; border:1px solid #ccc;'>Email</th>
              <th style='padding:8px; border:1px solid #ccc;'>Course</th>
            </tr>";
    while ($row = $result->fetch_assoc()) {
      echo "<tr>
              <td style='padding:8px; border:1px solid #ccc;'>" . $row["id"] . "</td>
              <td style='padding:8px; border:1px solid #ccc;'>" . $row["name"] . "</td>
              <td style='padding:8px; border:1px solid #ccc;'>" . $row["email"] . "</td>
              <td style='padding:8px; border:1px solid #ccc;'>" . $row["course"] . "</td>
            </tr>";
    }
    echo "</table>";
  }

  $conn->close();
}
?>

MySQL টেবিল তৈরি (students):

CREATE TABLE students (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(100) NOT NULL,
  course VARCHAR(100) NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Leave a Reply