如何使用 PDO 方法插入图像?
我收到这些错误消息:
警告:PDOStatement::execute(): MySQL server has gone away in C:\xampp\htdocs\testing\testform.php 第 21 行
警告:PDOStatement::execute(): Error reading result set's header in C:\xampp\htdocs\testing\testform.php on line 21
但是当我上传较小尺寸的图像时,它可以存储到数据库中,但图像名称不是图像名称。我的图像名称是“asdas”,但是当它存储到数据库中时,它变成了这样“?
PNG\r\n\Z\n\0\0\0\rIHDR\0\0|\0\08\0\0\0m?:\0\0\0sRGB\0???\0\0\ 0gAMA\0\0???a\0\0\0 pHYs\0\0?\0\0??o?d\0\0??IDATx^??`T??6????? ????c??{?R??*?? ??-=??? Ih!??F??HO?&B?U??s??????\'????Z?Z??a2?
<form action="testform.php" method="post" enctype="multipart/form-data">
<input name="image" type="file">
<input name="submit" type="submit" value="Upload Picture!">
</form>
<?php
if(isset($_POST['submit']))
{
$pdo = new PDO('mysql:dbname=forms1;host=localhost', 'root', 'root',
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if(substr($imageType,0,5)=="image")
{
$stmt = $pdo->prepare('INSERT INTO files (name,image) VALUES (:name,:image)');
$stmt->execute(array('name' => $imageData, 'image' => $imageType));
echo "Image Uploaded";
}
else
{
echo "Only images are allowed";
}
}
?>