Skip to content
PHP Logo

How can PHP developers effectively manage and expand image uploading functionality using MySQL?

To effectively manage and expand image uploading functionality using MySQL, PHP developers can create a database table to store image information such as file name, file path, and user ID. They can then use PHP to handle the image upload process, validate the file type and size, move the uploaded file to a designated folder, and insert the image details into the database.

php
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Handle image upload
if(isset($_FILES['image'])){
    $file_name = $_FILES['image']['name'];
    $file_tmp = $_FILES['image']['tmp_name'];
    $file_size = $_FILES['image']['size'];
    
    // Validate file type and size
    
    // Move uploaded file to designated folder
    move_uploaded_file($file_tmp, "uploads/" . $file_name);
    
    // Insert image details into database
    $sql = "INSERT INTO images (file_name, file_path, user_id) VALUES ('$file_name', 'uploads/$file_name', '1')";
    if ($conn->query($sql) === TRUE) {
        echo "Image uploaded successfully";
    } else {
        echo "Error uploading image: " . $conn->error;
    }
}

$conn->close();
?>