我试图从mysql数据库显示图片,但不知何故它不工作。图片是jpeg格式的。我使用一个简单的php代码与数据库连接文件和源文件。奇怪的是,如果我想直接从数据库下载图片,它仍然是一个二进制.bin文件。以下是我的代码:
db_connect.php:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=probe', $root);
?>
source.php:
<?php
include ‘db_connect.php’;
$query = “select * from users”;
$stmt = $con->prepare( $query );t
$stmt->bindParam($_GET['image']);
$stmt->execute();
$num = $stmt->rowCount();
if( $num ){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
header(“Content-type: image/jpeg”);
print $row['image'];
exit;
}else{
//if no image found with the given id,
//load/query your default image here
}
?>
在索引文件中我调用source。php来显示图片
<img src="../reg/source.php" >
这是SQL源代码:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` blob NOT NULL,
`image_type` varchar(100) NOT NULL,
`image_size` varchar(100) NOT NULL,
`image_name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=44 ;
这里有一些问题,我不确定我在注释中所说的那些花引号是否是您代码的一部分,包括);t
<=中的"t",如果它是您代码的一部分,请删除该"t"。
如果是,则‘ ’
和“ ”
需要分别改为'
和"
。
但是,您的连接使用$dbh
,而您在查询中使用$con
。
$dbh = new PDO('mysql:host=localhost;dbname=probe', $root);
^^^^ ^^^^^ unknown
和查询:
$stmt = $con->prepare( $query ); // minus the "t" of course.
^^^^
- 这会导致你的查询在这里失败。
然而,$root
是未知的,没有发布。
检查错误:
- http://php.net/manual/en/pdo.error-handling.php
- http://php.net/manual/en/function.error-reporting.php
将错误报告添加到文件的顶部,这将有助于查找错误。
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
旁注:显示错误应该只在登台时显示,而不应该在生产中显示。
同时在连接打开后添加$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
。
-
$dbh
或$con
,取决于您使用的变量。
这就是我在数据库中上传图片的方式。你是完全正确的,因为我使用的代码来自这个网站:http://www.phpro.org/tutorials/Storing-Images-in-MySQL-with-PHP.html。但是我对代码做了一些修改。
<?php
if(!isset($_FILES['userfile']))
{
echo '<p>Please select a file</p>';
}
else
{
try {
upload();
echo '<p>Thank you for submitting</p>';
}
catch(Exception $e)
{
echo '<h4>'.$e->getMessage().'</h4>';
}
}
?>
<?php
function upload(){
if(is_uploaded_file($_FILES['userfile']['tmp_name']) && getimagesize($_FILES['userfile']['tmp_name']) != false)
{
$size = getimagesize($_FILES['userfile']['tmp_name']);
$type = $size['mime'];
$imgfp = fopen($_FILES['userfile']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['userfile']['name'];
$maxsize = 100000;
if($_FILES['userfile']['size'] < $maxsize )
{
$dbh = new PDO("mysql:host=localhost;dbname=probe", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("UPDATE users SET image='$imgfp', image_type='$type', image_size='$size', image_name='$name' ");
$stmt->execute();
}
else
{
throw new Exception("File Size Error");
}
}
else
{
throw new Exception("Unsupported Image Format!");
}
}
?>
这是我检索图片的方法。
<div class="row">
<div class="col-md-3 col-sm-3">
<form
img src="../reg/source.php" method="get" ></form></div></div>