PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
CREATE DATABASE university; USE university; CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) NOT NULL );
Copy Clear
Copy Format Clear
<?php // Step 1: Connect to the database // Assuming $pdo is predefined // Step 2: Handle form submission to insert data if ($_SERVER["REQUEST_METHOD"] == "POST") { $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $email = $_POST['email']; try { $stmt = $pdo->prepare("INSERT INTO students (first_name, last_name, email) VALUES (:first_name, :last_name, :email)"); $stmt->execute([ 'first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, ]); } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } } // Step 3: Retrieve student data from the database try { $stmt = $pdo->query("SELECT id, first_name, last_name, email FROM students"); $students = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } ?> <!DOCTYPE html> <html> <head> <title>University Student Management</title> </head> <body> <h1>Student Management</h1> <!-- Step 4: Form to add new student --> <form method="POST"> <label>First Name:</label> <input type="text" name="first_name" required><br><br> <label>Last Name:</label> <input type="text" name="last_name" required><br><br> <label>Email:</label> <input type="email" name="email" required><br><br> <button type="submit">Add Student</button> </form> <!-- Step 5: Display student data --> <h2>Student List</h2> <table border="1"> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> </tr> <?php // Display all student records if (!empty($students)) { foreach ($students as $row) { echo "<tr>"; echo "<td>" . htmlspecialchars($row['id']) . "</td>"; echo "<td>" . htmlspecialchars($row['first_name']) . "</td>"; echo "<td>" . htmlspecialchars($row['last_name']) . "</td>"; echo "<td>" . htmlspecialchars($row['email']) . "</td>"; echo "</tr>"; } } ?> </table> </body> </html>
Show:  
Copy Clear