上传表单不起作用

时间:2014-01-21 14:48:28

标签: php mysql image

我正在尝试将图像上传到MySQL中的文件夹和路径。但是,当我尝试时,我得到错误。 这是表格:

<form action="upload.php" method="post" enctype="multipart/form-data">
     <input type="text" name="caption" /><br/><br />
     <input type="file" name="name" /><br />
     <input type="submit" id="upload" value="submit" />
</form>

这是upload.php

<?php

define('MAX_FILE_SIZE', 2000000);

$permitted = array('image/jpeg', 'image/jpeg', 'image/png', 'image/gif');

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

$caption = $_POST['userfile']['caption'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());

// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = "upload/" . $myFile;

if (in_array($fileType, $permitted) && $fileSize > 0
    && $fileSize <= MAX_FILE_SIZE) {

    $result = move_uploaded_file($tmpName, $path);

    if (!$result) {
        echo "Error uploading image file";
        exit;
    } else {
        $db = new mysqli("localhost", "root", "", "image");

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s<br/>", mysqli_connect_error());
        }

        $query = "INSERT INTO images (caption, name, size, type, file_path) VALUES (?,?,?,?,?)";
        $conn = $db->prepare($query);
        if ($conn == TRUE) {
            $conn->bind_param("siss",$caption, $myFile, $fileSize, $fileType, $path);
            if (!$conn->execute()) {
                echo 'error insert';
            } else {
               // echo "<img src=\"upload/'". $myFile .\"'/>";
                header("Location: index.php");
            }
        } else {
            die("Error preparing Statement");
        }
    }
} else {
    echo 'error upload file';
}
} else {
echo 'error'; **<==== I get this error**
}
?>

我得到的错误是最后一个Else / echo'错误'。我不知道会出现什么问题。

编辑://

现在成功将图像插入到DB但是没有插入NAME和PATH?

3 个答案:

答案 0 :(得分:2)

您的PHP代码

if (isset($_POST['upload'])) {}

但是在表单中没有任何名为upload的内容,因此请将提交按钮添加为

<input type="submit" id="upload" name="upload" value="submit" />

提交按钮需要您缺少的名称。

关于通知

你应该有像PHP文件中那样的东西

    $caption = $_POST['caption'];
    $fileName = $_FILES['userfile']['name'];
    $tmpName = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];

AND

<input type="file" name="name" /><br /> 

需要更改为

<input type="file" name="userfile" /><br />

答案 1 :(得分:1)

您缺少输入提交的名称属性,请尝试提供名称属性

<input type="submit" id="upload" value="submit" name="upload"/>

答案 2 :(得分:1)

$_FILES['userfile']

但是你的形式:

<input type="file" name="name" /><br />

应该是

<input type="file" name="userfile" /><br />

学习调试代码;)