【问题标题】:uploade image to mysql data base failure上传图片到mysql数据库失败
【发布时间】:2017-04-09 08:34:41
【问题描述】:

嘿,我有以下代码:

index.php

select.php

你也可以在 GitHub (simple-online-library) 中找到整个项目

它工作正常并将书名书作者书页保存在 mysql 数据库中,但它只是将图像名称和图像路径保存在数据库中我只想将图像移动到名为图像的新文件夹并尝试几种方法,但它们都不适合我。

【问题讨论】:

  • 首先你修复你的连接$connect = mysqli_connect($db_host, $db_username, $db_pass, $db_name);
  • $query 之前添加var_dump($file); 看看你得到了什么信息
  • @Mario 感谢您的回答,我修复了我的连接并添加了 var_dump 但它什么也没显示,只是浏览器警报框显示了 error. 第 3 行:$file = addslashes(file_get_contents($_FILES["images"]["tmp_name"]));
  • 是的,我猜你有一个空字符串,因为你没有处理来自不存在的 form 的 $_FILES['images']。阅读此内容,您就会明白php.net/manual/en/features.file-upload.post-method.php 您需要此<form enctype="multipart/form-data" action="" method="POST"> 才能上传文件。
  • 我更新了我的代码和我的问题。

标签: php mysql image upload


【解决方案1】:

应该固定如下

 <?php  
require_once("db.php");
$file = addslashes(file_get_contents($_FILES["images"]["tmp_name"]));
 $sql = "INSERT INTO test1(name, lastname, age , images) VALUES('".$_POST["name"]."', '".$_POST["lastname"]."', '".$_POST["age"]."', '".$file."')";  
 if(mysqli_query($connect, $sql))  
 {  
  echo 'infos saved';  
 }  
 ?> 

更新

您的 AJAX 脚本只发送文件名,不发送图像。正确的 JS 应该和下面的类似。

$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{
     // do something ex. $('#loading').hide();
}
});

【讨论】:

  • 为什么要存储临时名称?他以后如何获得图像?
  • @Mario 使用 file_get_contents 读取文件内容,它应该可以工作
  • @Оzgur 感谢您的回答,我使用了旅游代码并更新了我的代码,但仍然没有任何变化,也没有任何内容上传到数据库中的图像行,它只是显示error in browser alert box. 第 3 行:$file = addslashes(file_get_contents($_FILES["images"]["tmp_name"]))‌​;
  • @jackson 在您的 html 代码中我看不到
    元素...您的案例有一个教程。你可以下载并继续它。 formget.com/ajax-image-upload-php
  • @Оzgur 因为我不使用表单我通过使用 java 将数据发布到数据库。还是谢谢你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 2013-04-22
  • 1970-01-01
  • 2015-05-27
相关资源
最近更新 更多