Untitled

 avatar
unknown
plain_text
20 days ago
1.3 kB
4
Indexable
<?php
include('dbcon.php'); // Include database connection

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form data
    $first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
    $last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
    $age = intval($_POST['age']); // Ensure age is an integer
    $category = intval($_POST['category']); // Ensure category is an integer
    
    // Image upload handling
    $image = $_FILES['image']['name'];
    $target = "images/" . basename($image); // Create the folder images in the root directory before running this code

    // Insert data only if image is uploaded successfully
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        $query = "INSERT INTO students (first_name, last_name, age, image, category) 
          VALUES ('$first_name', '$last_name', $age, '$image', $category)";

        if (mysqli_query($conn, $query)) {
            // Redirect to index.php with success message
            header("Location: index.php?success=Student added successfully");
            exit();
        } else {
            echo "Error: " . $query . "<br>" . mysqli_error($conn);
        }
    } else {
        echo "Failed to upload image.";
    }
}

// Close database connection
mysqli_close($conn);
?>
Editor is loading...
Leave a Comment