如何将图像添加到我的PHP博客?

时间:2017-01-26 13:06:26

标签: php mysql sql

我已经使用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更容易吗?我不知道如何在上传后将图片显示在右侧博文中。

祝你好运, Tobias Dybdahl

2 个答案:

答案 0 :(得分:0)

您可以将文件上传到服务器,然后将文件名存储在数据库中,例如名为&#34; blogimg&#34;的列。

然后在显示博客帖子的代码中,您可以添加此行以显示图像:

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

答案 1 :(得分:0)

您需要将图像上传到目录并将图像名称保存在数据库中 在那之后右边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;
    }
}
?>