图像无法上传到数据库

时间:2018-01-18 09:12:20

标签: php mysql blob

我创建了一个带有表单的php脚本,它应该将一些数据插入到数据库中,它实际上会添加文本和ID,但它不会添加文件。

数据库如下所示:

数据库名称:highmob_comenzi 表名:球员 在表中我们得到3行: ID(auto_increment) name(我们从表单中插入的名称) schite(应该上传文件的地方)类型:blob Colation:none,all none

这是我到目前为止尝试的脚本

 <?php
 include('connect-db.php');
 ?>
 <?php
 function renderForm($name, $schita, $error)
 {
 ?>

 <?php
 if ($error != '')
 {
 echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
 }
 ?>
  <form action="" method="post" enctype="multipart/form-data" >
  <input type="hidden" name="id" value="<?php echo $id; ?>"/>
  <input type="hidden" name="name" value="<?php echo $name; ?>"/>
  <input type="file" id="schita" name="schita" >
  <button type="submit" name="submit">Add Data</button>
  </form>
 <?php
 }
 include('connect-db.php');
 if (isset($_POST['submit']))
 {
 $name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
 $schita = mysql_real_escape_string(htmlspecialchars($_POST['schita']));
 if ($name == '')
 {
 $error = 'Error !!';
 renderForm($name, $schita, $error);
 }
 else
 {
 mysql_query("INSERT players SET name='$name', schita='$schita'")
 or die(mysql_error());
 header("Location: mobila.php");
 }
 }
 else
 {
 renderForm('','','','','');
 }
 ?>

当我们在表单中插入数据时,此脚本为每个ID创建一个页面 比如pagename.php?id = 4

我希望当我打开页面创建页面后填写表单,只在该页面上查看上传的文件,

知道为什么它不起作用?

4 个答案:

答案 0 :(得分:0)

使用$_FILES获取请求文件,还需要确认您的mysql字段(schita)是blob类型

答案 1 :(得分:0)

您需要更正插入查询。您缺少'into'关键字。将查询更改为:

mysql_query("INSERT into players SET name='$name', schita='$schita'");

答案 2 :(得分:0)

您需要将图像转换为base64,然后将其保存到数据库。

// Select file type
  $target_file = basename($_FILES["file"]["name"]); 
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  // Convert to base64 
  $image_base64 = base64_encode(file_get_contents($_FILES['schita']['tmp_name']) );
  $image = 'data:image/'.$imageFileType.';base64,'.$image_base64;

  // Insert record
  $query = "INSERT into players(schita) values('".$image."')";
  mysqli_query($con,$query);

答案 3 :(得分:0)

我已设法使用此脚本上传文件

 <?php
 $dbh = new PDO("mysql:host=localhost;dbname=highmob_comenzi", "highmob", "PW");
 if(isset($_POST['btns'])){
     $name = $_FILES['myfile']['name'];
     $type = $_FILES['myfile']['type'];
     $data = file_get_contents($_FILES['myfile']['tmp_name']);
     $stmt = $dbh->prepare("UPDATE players SET data='$myfile', name='$name', mime='$type' WHERE id='$id'");
     $stmt->bindParam(1,$name);
     $stmt->bindParam(2,$type);
     $stmt->bindParam(3,$data);
     $stmt->execute();
 }
 ?>
 <!-- form -->
 <form method="post" enctype="multipart/form-data">
 <input type="file" name="myfile"/>
 <button name="btns"> Incarca Schita </button>
 </form>
 <!-- display data -->
 <?php
 $stat = $dbh->prepare("select * from players");
 $stat->execute();
 while($row = $stat->fetch()){
     echo "<a target='_blank' href='viewschita.php?id=".$row['id']."'>".$row['name']."</a>";
 }

 ?>

问题是我不知道如何建立文件的链接,任何想法如何?