PHP - 成功更新文件但更新文本失败

时间:2017-03-17 07:08:34

标签: php mysqli

我为文本和文件制作了一个简单的更新表单。这是我的代码

<?php
require("config.php");
$id = $_GET['id'];

$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
while ($row = $result->fetch_assoc())
{   

?>

<html><head><title>test</title></head>
<body>

<form method="POST" action="" enctype="multipart/form-data">

    ID: <?php echo $id; ?><br>
    <input type="hidden" name="id" value="<?php echo $id; ?>" />

    Contract Title
    <input type="text" name="contract_title" value="<?php echo $row['contract_title']; ?>" /><br>

    Upload File:
    <?php echo $row['filename'] ?>
    <input type="file" name="upload"/><br>  
    <input type="submit" name="edit" value="Submit"/>
</form>
</body>
</html>

<?php
}

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

if ($_FILES['upload']['size'] != 0 ){

$contract_title = $con->real_escape_string($_POST['contract_title']);

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$query = "UPDATE `contracts` set `filename` = '$filename',`filedata` = '$filedata', `filetype` = '$filetype',`filesize` = '$filesize' WHERE `id` = '$id' " ;

if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
    echo "Error:<br>" . $con->error;
}

} else {

$contract_title = $con->mysqli_real_escape_string($_POST['contract_title']);

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$query = "UPDATE `contracts` set `filename` = '$filename', `filetype` = '$filetype',`filesize` = '$filesize' WHERE `id` = '$id' " ;

if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}

}
$con->close(); 
}   

?>

点击提交按钮后,它成功更新了文本上传文件。我不想从post更改为get方法,因为这会对上传文件进程产生同样的问题。我该如何解决?

2 个答案:

答案 0 :(得分:0)

最有可能的是,您没有正确获取$ filename。尝试调试并打印$ _FILES [&#39;上传&#39;] [&#39;名称&#39;],看看你得到了什么(你可以json_encode并查看你想要访问的结果)。其余的代码似乎没问题

答案 1 :(得分:0)

所有这段时间在代码中查找错误数小时之后,这是一个我错过的简单错误!

$query = "UPDATE `contracts` set `contract_title` = '$contract_title', `filename` = '$filename',`filedata` = '$filedata', `filetype` = '$filetype',`filesize` = '$filesize' WHERE `id` = '$id' " ;

我没有在查询中输入contract_title!我的上帝