douyong5476 2017-03-05 18:53
浏览 44
已采纳

尝试将上载文件的路径插入MySQL时,会创建副本

I am trying to insert the paths to one user uploaded image($picpath), one user input($uname) and to an html file with variable content($profilepath) into a MySQL table like so:

<?php
$target_dir = 'uploads/';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;


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

$temp = explode(".", $_FILES["fileToUpload"]["name"]);
$imageFileType = end($temp);

$random = uniqid();

$imgname = "img$random.$imageFileType";
$picpath = "uploads/$imgname";

if ($uploadOk == 0) {
echo "sorry not able to upload file";
}
else {
    if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], "uploads/ . $imgname)) {
        echo "the file " .$imgname. " has been uploaded!";
    }
    else {
        echo "sorry there was an error.";
    }
}


$uname = $_POST['uname'];


$filecount = count(glob("usertest/*.html"));

$filename = "user" .($filecount+1).".html";

$profilepath = "usertest/$filename";

$myfile = fopen("usertest/$filename", "w") or die("unable to create file");

$html = "<html><body><h1>this is" .$uname."'s profile</h1></body></html>";

fwrite($myfile, $html);

fclose($myfile);


$servername = "127.0.0.1";
$username = "username";
$password = "Password";
$dbname = "database";

// Create connection
$conn =  new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}



$sql = "INSERT INTO users(id, name, profilepath, picpath) VALUES (NULL, '$uname','$picpath', '$profilepath')";



if ($conn->query($sql) === TRUE) {

    echo "New record created!";
}


else {
    echo "Error.";
}




$conn->close();





?>

From the following HTML/JS:

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script>

$('.button').click(function(){
     var unameValue = $('input:text').val();
     var actionValue = $(this).val();
     var ajaxurl = 'upload.php',
     data = {
        'uname': unameValue,

     };
     $.post(ajaxurl, data, function(response) {
         alert("success!!!!");
     });
     });
     </script>
     </head
     <body>
     <form method="POST">
     <input id="userinput" type="text" name="uname" value="peter" />


     </form>  

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" class="button" value="submit" />
</form>
</body>
</body>
</html>

However when I run the code I see that two html files have been created(when only wanting one). What is more, they are named differently (e.g. user1.html, user2.html). Also when I check the MySQL database the following appears:

ID   Name    picpath              profilepath

1    Peter   usertest/user1.html  uploads/img19ckdovj239si.
2            usertest/user2.html  uploads/img19ckdovj239si.png
3    George  usertest/user3.html  uploads/img19ckdovuv34yu.
             usertest/user4.html  uploads/img19ckdovuv34yu.png

And so on(the random image numbers are made up). It is really weird! I should also add that sometimes the two images would have the same uniqid()(as seen above) and sometimes they wouldn't. I tried everything I could find online, but it seems like nobody has encountered this problem! Any help would be greatly appreciated!
Thanks!


EDIT:

This is what the html should look like (it's much simpler, and without js!):

<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload"/>
    <input id="userinput" type="text" name="uname" value="peter" />
    <input type="submit" class="button" value="submit" />
</form>
</body>
</body>
</html>

It uses the same PHP.

  • 写回答

1条回答 默认 最新

  • dongmu1914 2017-03-05 19:04
    关注

    actually is not weird! you send data twice! (with post and ajax!) so your form send twice. Clear ajax function or action and method from form tag like this :

    <!DOCTYPE html>
    <html>
    <head>
    
    <script type="text/javascript" src="jquery-3.1.1.js"></script>
    <script>
    
    $('.button').click(function(){
         var unameValue = $('input:text').val();
         var actionValue = $(this).val();
         var ajaxurl = 'upload.php',
         data = {
            'uname': unameValue,
    
         };
         $.post(ajaxurl, data, function(response) {
             alert("success!!!!");
         });
         });
         </script>
         </head
         <body>
         <form method="POST">
         <input id="userinput" type="text" name="uname" value="peter" />
    
    
         </form>  
    
    <form >
        Select image to upload:
        <input type="file" name="fileToUpload" id="fileToUpload">
        <input type="submit" class="button" value="submit" />
    </form>
    </body>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在