I’m building a simple blog site using PHP, and I am new to PHP. I’m stuck with solving the issue of the arrangement of both text and images when users post content.
Issue Details
Text Issue: The text displayed is not the same as what the user posted; it’s showing different text.
Image Misalignment and Duplication: Images sometimes don’t appear in the correct order, or they duplicate.
Multiple Image Uploads: When users try to upload multiple images, only one or two images get posted.
Here’s the code I’m using for handling the content (text and images):
PHP Code for Handling Post Request
$tmpName) {
$fileName = basename($_FILES['profilePictures']['name'][$key]);
$fileTmp = $tmpName;
$fileSize = $_FILES['profilePictures']['size'][$key];
$imageFileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
$allowedTypes = ["jpg", "jpeg", "png"];
// Validate file type and size
if (in_array($imageFileType, $allowedTypes) && $fileSize <= 5000000) {
if (!is_dir($targetDir)) {
mkdir($targetDir, 0777, true);
}
$uniqueFileName = uniqid() . "_" . $fileName;
$targetFile = $targetDir . $uniqueFileName;
if (move_uploaded_file($fileTmp, $targetFile)) {
$imagePaths[] = $targetFile;
}
}
}
}
// Save post to the database
$imagesSerialized = serialize($imagePaths);
$sql = "INSERT INTO posts (content, image_path) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $content, $imagesSerialized);
if ($stmt->execute()) {
echo "Post submitted successfully!";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
}
?>
HTML Form for Image and Text Input
JavaScript for Inserting Images and Saving Content
function insertImageIntoDiv(event) {
const fileInput = event.target;
const editableDiv = document.getElementById('editableDiv');
if (fileInput.files) {
Array.from(fileInput.files).forEach((file) => {
const reader = new FileReader();
reader.onload = function (e) {
const imgElement = ``;
editableDiv.innerHTML += imgElement;
};
reader.readAsDataURL(file);
});
}
}
function submitContent() {
const editableDiv = document.getElementById('editableDiv');
const hiddenContent = document.getElementById('hiddenContent');
hiddenContent.value = editableDiv.innerHTML;
}
Any help would be greatly appreciated! Thank you