【问题标题】:Uploading image in PHP save filepath to database在PHP中上传图像保存文件路径到数据库
【发布时间】:2026-01-05 19:15:02
【问题描述】:

我有一个工作图像上传,将图像保存到上传目录。我现在正在尝试使用 PDO 将文件路径和图像名称插入到我的 mysql 数据库中。

没有抛出错误,但插入数据库不起作用。 SQL 语句似乎会在程序作为任何 echo 运行时停止程序,因为它不会输出任何内容。

这是我的输入表单:

<!DOCTYPE html>
<html>
<body>

<form action="views/imageupload/imageupload.php" method="post" enctype="multipart/form-data">
    <label>Image Tag: <input type="text" name="img_tag"></label>
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

这是我的 php 上传:

<?php
$target_dir = "uploads/";
$target_store_url = basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

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;
    }
}

$image_insert_tag = $_POST['img_tag'];
$image_insert_SQL = "INSERT INTO images VALUES ('','$image_insert_tag', $target_store_url)";
$insert_exec = $link->query($image_insert_SQL);

// Check if uploadOK = 0 because of an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

//Upload file - code
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {

        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

?>

为澄清起见,这两个文件都位于“views/imageupload”中,并且在该目录中还有另一个名为“uploads”的目录,用于存储图像。当在导航栏中单击该页面时,所有这些都是从包含该页面的索引页面访问的。

我一直在阅读有关这些方面的大量其他问题,但我还没有设法解决它。我尝试这样做的原因是因为我要创建另一个页面,该页面将是一个画廊并显示所有上传的图像。为此,我将使用一个语句来提取所有图像 URL 并显示它们。我曾考虑将图像本身存储在数据库中,但被告知不建议这样做。

【问题讨论】:

  • 要么检查日志是否有错误,要么打开php错误报告。
  • 您的代码容易受到SQL injection attacks 的攻击。您应该使用mysqliPDO 准备好的语句和this post 中描述的绑定参数。
  • $target_store_url 这是一个字符串;你需要把它当作一个。如果您想作为 BLOB 插入,则需要对其进行转义。
  • “但被告知不建议这样做。” - Storing Images in DB - Yea or Nay?
  • @SloanThrasher - 我有错误报告(它包含在通过索引包含在我的“database_connect”文件中。

标签: php mysql database image pdo


【解决方案1】:

您使用带有 php PDO 的我的 sql 数据库。在 php PDO 中有一些角色可以将数据插入到您必须遵循的角色的基础中。

// prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute(); 

我希望如果您尝试像这样插入它不会正常工作。

如需更多帮助,请参阅。 https://php.net/manual/en/pdo.prepared-statements.php

【讨论】:

    最近更新 更多