我正在尝试直接将图像插入到mysql数据库表中。在我的数据库中,我总是得到[BLOB - 0B]。它不会将图像插入表格中。我也没有得到任何错误。我很困惑..
PHP
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
include('config.php');
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
}
try
{
$stmt = $conn->prepare("INSERT INTO images ( picture ) VALUES ( '$data' )");
// $stmt->bindParam(1, $data, PDO::PARAM_LOB);
$conn->errorInfo();
$stmt->execute();
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}
HTML
<form action="upload.php" method="post">
<input id="image" name="image" type="file" />
<input type="submit" value="Upload" />
</form>
答案 0 :(得分:5)
你几乎得到它,你希望PDO::PARAM_LOB
成为你上面创建的文件指针,而不是读取fp的结果
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'rb'); // read binary
}
try
{
$stmt = $conn->prepare("INSERT INTO images ( picture ) VALUES ( ? )");
$stmt->bindParam(1, $fp, PDO::PARAM_LOB);
$conn->errorInfo();
$stmt->execute();
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}