php图片保存入mysql数据库失败处理办法
发布时间:2022-07-05 15:53:24 所属栏目:PHP教程 来源:互联网
导读:图片保存数据库并不是一个明智的做法,我们多半是把图片保存到服务器,然后把图片地址保存到数据库,这样我们每次只要读出图片地址就可以显示了,但下面我还是来介绍一个图片保存到mysql数据库的问题解决办法,代码如下: require class/db.php; $fileName = a1.jp
图片保存数据库并不是一个明智的做法,我们多半是把图片保存到服务器,然后把图片地址保存到数据库,这样我们每次只要读出图片地址就可以显示了,但下面我还是来介绍一个图片保存到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丶> 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); 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); }//开源代码phpfensi.com 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,代码如下: <html> <head> <title>上传图片</title> </head> </form> </body> </html> 后台处理upimage.php代码如下: <?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)){ //判断上传文件是否为空,文件是不是上传的文件 if(mysql_query("insert into images(name,type,image) values('".$name."','".$type."',0x".$imgdata.")")) echo "<center>插入成功!<br><br><a href='disimage.php'>显示图片</a></center>"; else echo "<center>插入失败!</center>"; mysql_close(); }else echo "<center>请先选择图片!<br><br><a href='image.html'>点此返回</a></center>"; } else echo "<center>请先选择图片!<br><br><a href='image.html'>点此返回</a></center>"; ?> 显示图片disimage.php,代码如下: <?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(); ?> (编辑:PHP编程网 - 黄冈站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |