I faced some problems with the file upload and updating the database. The image sometimes doesn’t upload correctly, or the path isn’t saved properly in the database. How can I troubleshoot and fix these issues in the current code?
<?php
include 'db.php';
session_start();
$nic = $_SESSION["nic"];
// Retrieve profile data
$sql = mysqli_query($conn, "SELECT * FROM update_profile WHERE nic ='{$nic}'");
if (mysqli_num_rows($sql) > 0) {
$profile = mysqli_fetch_assoc($sql);
} else {
$profile = null;
}
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
$nic = $_SESSION["nic"]; // Assuming the NIC is stored in the session
if (isset($_POST["submit"])) {
$email = $_POST["email"];
$school = $_POST["school"];
$mobile = $_POST["mobile"];
$stream = $_POST["subject_stream"]; // Changed to match the form field name
$address = $_POST["address"];
$profile_pic = $_FILES["profile_pic"];
if (!empty($email) && !empty($school) && !empty($mobile) && !empty($stream) && !empty($address) && !empty($nic)) {
if ($profile_pic && $profile_pic['error'] == UPLOAD_ERR_OK) {
$target_file = dirname(__FILE__)."/profile_pictures/{$nic}_{$profile_pic["name"]}";
$uploaded = move_uploaded_file($profile_pic["tmp_name"], $target_file);
}
// Prepare the SQL statement
$stmt = mysqli_prepare($conn, "UPDATE update_profile SET email = ?, school = ?, mobile = ?, stream = ?, address = ?, pic = ? WHERE nic = ?");
// Bind parameters
$imageUrl = "/vv/std/profile_pictures/"."{$nic}_{$profile_pic["name"]}";
$pic = isset($target_file) && isset($uploaded) && $uploaded ? $imageUrl : "";
mysqli_stmt_bind_param($stmt, "ssissss", $email, $school, $mobile, $stream, $address, $pic, $nic);
// Execute the statement
if (mysqli_stmt_execute($stmt)) {
// Close the statement
mysqli_stmt_close($stmt);
// Redirect to profile.php
header("Location: profile.php");
exit;
} else {
$error_message = "Error: " . mysqli_stmt_error($stmt);
}
} else {
$error_message = "All fields are required.";
}
}
// Retrieve existing profile data
$sql = mysqli_query($conn, "SELECT * FROM update_profile WHERE nic ='{$nic}'");
if (mysqli_num_rows($sql) > 0) {
$profile = mysqli_fetch_assoc($sql);
}
?>
I attempted to update the user profile by uploading an image and saving its path to the database. I expected the image to upload successfully and the correct path to be stored in the database. However, the image sometimes fails to upload, or the path is not correctly saved, leading to incomplete profile updates.