簡體   English   中英

如何將圖片添加到我的 PHP 博客?

[英]How do I add images to my PHP blog?

我用 PHP 和 mysql 數據庫為我的網站制作了一個博客,我可以在其中添加來自管理站點 (www.website.com/admin) 的博客文章,並將它們顯示在我的網站 (www.website.com) 上。 它工作正常,但我也想添加圖片

這是我添加的代碼:

if (isset($_POST['submit'])) {

    $blogtitle = htmlentities($_POST['blogtitle'], ENT_QUOTES);
    $blogdate = htmlentities($_POST['blogdate'], ENT_QUOTES);
    $blogdesc = htmlentities($_POST['blogdesc'], ENT_QUOTES);

// check that firstname and lastname are both not empty
if ($blogtitle == '' || $blogdesc == '') {

    $error = 'Please fill in all required fields';
    renderForm($blogtitle, $blogdesc, $error);

} else {

// insert the new record into the database
if ($stmt = $mysqli->prepare("INSERT blog_posts (blogtitle, blogdate, blogdesc) VALUES (?, ?, ?)")) {
    $stmt->bind_param("sss", $blogtitle, $blogdate, $blogdesc);
    $stmt->execute();
    $stmt->close();
} else {
    echo "ERROR: Could not prepare SQL statement.";
}
    header("Location: website.php");
}

} else {
renderForm();
}
}

// close the mysqli connection
$mysqli->close();

還有我用於顯示博客文章的代碼

/.../
while ($row = $result->fetch_object()) {

    echo "<div>";
    echo "<td>" . $row->blogtitle . "</td>";
    echo "<td>" . $row->blogdate . "</td>";
    echo "<td>" . $row->blogdesc . "</td>";
    echo "</div>";
 }

我知道如何制作upload.php,但是上傳到mysql更容易嗎? 我不知道如何在上傳后獲得正確博客文章中顯示的圖像。

最好的問候,托比亞斯·迪布達爾

您可以將文件上傳到服務器,然后將文件名存儲在數據庫中,例如名為“blogimg”的列。

然后在顯示博客文章的代碼中,您可以添加這一行來顯示圖像:

echo "<td><img src='" . $row->blogimg . "' /></td>";

您需要將圖像上傳到目錄並將圖像名稱保存在數據庫中,然后在 img 標簽中的圖像的 url 中,並從數據庫中獲取圖像名稱

你的 html 表單

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

你的 php 代碼

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM