用PHP将文件上传到mysql

时间:2017-01-16 16:48:26

标签: php mysql

我真的一直在努力解决我的问题。 我看了整个互联网,但找不到任何理由为什么我一直有这个问题。

我的文件确实被发送到我服务器上的'uploads'文件,但细节不会发送到mysql db。我做错了什么?

的index.php

    <?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="body">
    <form action="upload.php" method="post" enctype="multipart/form-data">

    <div class='container'>
    <label for='voornaam' >Naam*: </label><br/>
    <input type='text' name='voornaam' />
    </div>
    <input type="file" name="file" />
    <button type="submit" name="btn-upload">upload</button>
    </form>
    <br /><br />

</div>
</body>
</html>

upload.php的

<?php
include 'dbconfig.php';
if($_FILES["file"]["error"]>0)
{
    echo "FILE ERROR";
    die();
}
$filename = "uploads/".$_FILES["file"]["name"];
// move file to a folder
 if(move_uploaded_file($_FILES["file"]["tmp_name"], $filename))
 {
  $sql="INSERT INTO tbl_uploads(name, file) VALUES('voornaam',$filename')";
  mysql_query($sql);
  ?>
  <script>
  alert('successfully uploaded');
        window.location.href='index.php?success';
        </script>
  <?php
 }
 else
 {
  ?>
  <script>
  alert('error while uploading file');
        window.location.href='index.php?fail';
        </script>
  <?php
 }
?>

2 个答案:

答案 0 :(得分:0)

首先,请阅读PDO / MYSQLI。

关于您的问题,您必须删除&#39;

enter image description here

答案 1 :(得分:0)

  • 首先使用不推荐使用的Mysql_*函数删除 准备好的陈述

这里的解决方案

upload.php的

<?php
include 'dbconfig.php';
if($_FILES["file"]["error"]>0)
{
    echo "FILE ERROR";
    die();
}
$filename = "uploads/".$_FILES["file"]["name"];
// move file to a folder
if(move_uploaded_file($_FILES["file"]["tmp_name"], $filename))
{
    $sql="INSERT INTO tbl_uploads(name, file) VALUES('voornaam','$filename')";
    mysqli_query($db,$sql);
    ?>
    <script>
        alert('successfully uploaded');
        window.location.href='index.php?success';
    </script>
    <?php
}
else
{
    ?>
    <script>
        alert('error while uploading file');
        window.location.href='index.php?fail';
    </script>
    <?php
}
?>

dbconfig.php

<?php
//header('Content-Type: text/html; charset=ISO-8859-1');
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'tbl_uploads');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>