2017-04-27 114 views
0

我试图上传图像到mysql数据库,但是当我上传图像时,我收到确认消息,但是当我检查我的数据库图像行是空的,我做错了什么?插入图像到数据库

<?php include "connection.php"; ?> 
 
<?php 
 
$n=$_POST["num"]; 
 
$t=$_POST["texto"]; 
 
$i=$_POST["imagem"]; 
 
$image = addslashes(file_get_contents($_FILE['$i']['tmp_name'])); 
 

 
if ($connect->connect_error){ 
 
\t die("Connection failed: " . $connect->connect_error); 
 
} 
 

 
$sql = "UPDATE servicos SET texto='$t', imagem='{$image}' where nmr=$n" ; 
 

 
if ($connect->query($sql) === TRUE) { 
 
\t echo "informação atualizada"; 
 
} else { 
 
\t echo "Error: " . $sql . "<br>" . $connect->error; 
 
} 
 

 
$connect->close(); 
 
?>
<html> 
 
<body> 
 
<div class="formulario" style="width: 100%; height: 100%;"> 
 
<form enctype="multipart/form-data" name="form1" target="apresenta" method="post" action="menu2.php" style="position:absolute; top:70;left:10 
 
border:thin; border-style:none;"> 
 
<label> Atualizar dados </label><br> 
 
Numero:&nbsp;<input type="text" name="num" value=""><br> 
 
Texto:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="texto" value=""><br> 
 
Imagem:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="file" name="imagem" value=""><br> 
 
<input type="submit" name="submit" value="enviar">&nbsp;&nbsp;&nbsp; 
 
<input type="reset" value="limpar"> 
 
</form> 
 
</div> 
 
</body> 
 
</html>

+0

为什么使用addslashes(file_get_contents(?请参见:https://www.w3schools.com/php/php_file_upload.asp –

+0

)为什么要增加数据库大小?不好的做法是将文件存储在在数据库中,您应该借助文件系统将它们存储在服务器上,如果您仍然希望将这些文件保存在数据库中,您首先需要将它们转换为base64格式或以我们可以保存在数据库中的任何其他格式。 – itzmukeshy7

+0

A处理这个问题的常用方法是将图像存储在文件系统中,然后在数据库中存储图像的路径 – fredrover

回答

0

除了所有的评论,指出 “你不应该存储在表中的文件,因为......”,这是什么工作(用PHP 7):

<?php 
if(isset($_POST['submit'])) { 
    var_dump($_FILES); 
    $dbh = new PDO("mysql:host=127.0.0.1;dbname=test", "root", ""); 
    $stm = $dbh->prepare("INSERT INTO test_img (cont) VALUES (?)"); 
    $stm->execute(array(file_get_contents($_FILES['fileinput']['tmp_name']))); 
} 
?> 
<form method="post" enctype="multipart/form-data"> 
    File: <input type="file" name="fileinput"><br> 
    <button name="submit">Upload</button> 
</form> 

可能的错误来源:

  • $connect->query($sql) === TRUE应该是$connect->query($sql) !== false
  • UPDATE的条目不存在
  • imagem='{$image}'是一个比较“哈克”的方式做插入变量,使用串联:$sql = "UPDATE servicos SET texto='".$t."', imagem='".$image."' where nmr=".$n;

希望这有助于。