Table of Contents
php将图片保存入mysql数据库失败的解决方法,
Home php教程 php手册 php将图片保存入mysql数据库失败的解决方法,

php将图片保存入mysql数据库失败的解决方法,

Jun 13, 2016 am 09:18 AM
mysql php picture Solution

php将图片保存入mysql数据库失败的解决方法,

本文实例分析了php将图片保存入mysql数据库失败的解决方法。分享给大家供大家参考。具体分析如下:

图片保存数据库并不是一个明智的做法,我们多半是把图片保存到服务器,然后把图片地址保存到数据库,这样我们每次只要读出图片地址就可以显示了,但下面我还是来介绍一个图片保存到mysql数据库的问题解决办法,代码如下:

复制代码 代码如下:

require 'class/db.php';
$fileName = "a1.jpg";
$fp = fopen($fileName, "r");
$img = fread($fp, filesize($fileName));
fclose($fp);
 
$db->execute("insert db2.testimg (`img`) values ('$img') ;");


报错:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`?绶q?仳!????1丶>,Mo?'^WZ4in??T春??????U?楹\?' at line 1

代码如下:

复制代码 代码如下:

$img = fread($fp, filesize($fileName));
$img = addslashes($img)

继续报错,各种搜索,百度里的结果都是addslashes,要不就是addslashes也没有的,真是扯淡啊.

复制代码 代码如下:

base64_decode
$img = base64_encode($img);

插入成功,图片文件17.0k,出来进行base64_decode,显示正常,找到个16进制的办法:

复制代码 代码如下:

$img = bin2hex($img);

有效,输出不用解密,存入数据库很大 25K,比base64还坑爹呢,再找,后来,后来,发现phpmyadmin直接上传的图片文件可以用文件比base64的小,文件12.8k.

翻phpmyadmin 源代码,common.lib.php文件183有个神奇的函数,代码如下:

复制代码 代码如下:

function PMA_sqlAddslashes($a_string = '', $is_like = false, $crlf = false, $php_code = false)
{
    if ($is_like) {
        $a_string = str_replace('\', '\\\\', $a_string);
    } else {
        $a_string = str_replace('\', '\\', $a_string);
    }
 
    if ($crlf) {
        $a_string = str_replace("n", 'n', $a_string);
        $a_string = str_replace("r", 'r', $a_string);
        $a_string = str_replace("t", 't', $a_string);
    }
 
    if ($php_code) {
        $a_string = str_replace(''', '\'', $a_string);
    } else {
        $a_string = str_replace(''', '''', $a_string);
    }
 
    return $a_string;
} // end of the 'PMA_sqlAddslashes()' function$img = PMA_sqlAddslashes($img);


文件大小12.8K 和phpmyadmin的一样大.

例,前台image.html,代码如下:

复制代码 代码如下:



  上传图片

 


 
 File:
 



后台处理upimage.php代码如下:

复制代码 代码如下:

 //向数据库中插入图片
 $imgfile=$_FILES['imgfile'];
 $submitbtn=$_POST['submitbtn'];
 if($submitbtn=='OK' and is_array($imgfile)){
 $name=$imgfile['name'];  //取得图片名称
 $type=$imgfile['type']; //取得图片类型
 $size=$imgfile['size'];  //取得图片长度
 $tmpfile=$imgfile['tmp_name'];  //图片上传上来到临时文件的路径
 if($tmpfile and is_uploaded_file($tmpfile)){  //判断上传文件是否为空,文件是不是上传的文件
  //读取图片流
  $file=fopen($tmpfile,"rb");
  $imgdata=bin2hex(fread($file,$size));  //bin2hex()将二进制数据转换成十六进制表示
  fclose($file);
 
  $mysqli=mysql_connect("localhost","root","123456″);  //连接数据库函数
  mysql_select_db("test");  //选择数据库
  //插入出数据库语句,图片数据前要加上0x,用于表示16进制数
  if(mysql_query("insert into images(name,type,image) values('".$name."','".$type."',0x".$imgdata.")"))
   echo "

插入成功!

显示图片
";
  else
   echo "
插入失败!
";
  mysql_close();
 }else
 echo "
请先选择图片!

点此返回
";
} else
 echo "
请先选择图片!

点此返回
";
?>
显示图片disimage.php,代码如下:

复制代码 代码如下:

 mysql_connect("localhost","root","123456″);
 mysql_select_db("test");
 //显示最新插入的那张图片
 $result=mysql_query("select image from images where id=(select max(id) from images)");
 $row=mysql_fetch_object($result);
 header("Content-Type:image/pjpeg");
 echo $row->image;
 mysql_close();
?>


结论:

PMA_sqlAddslashes好用 文件12.8k 和原来图片一样大

bin2hex 16进制 好用文件25K

base64_encode 好用,出来的文件需要base64_decode 17K

addslashes 不好用,继续报错,注明,在某些windows机器上addslashes好用.

希望本文所述对大家的php程序设计有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles