如何从PHP将.pdf文件以BLOB形式存储到MySQL中?
编辑添加:以下代码已过时,在PHP 7中无法使用。请参见答案底部的注释获取更多详细信息。
假设表结构包括一个整数ID和一个Blob DATA列,并且假设使用MySQL函数与数据库进行交互,您可能可以像这样操作:
$result = mysql_query 'INSERT INTO table (
data
) VALUES (
\'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';
$result = mysqli_query ($db, 'INSERT INTO table (
data
) VALUES (
\'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');
最理想的方法是使用MySQLI/PDO准备语句。
mysqli_real_escape_string()
调用中的第1个和第2个参数应该交换位置,参考:http://php.net/manual/en/mysqli.real-escape-string.php。//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
mysqli_real_escape_string()
也需要数据库连接。Gordon,完成后可以通知我吗? - Funk Forty Ninermysqli_query 'INSERT
也应该有括号,就像这样mysqli_query($con, 'INSERT... . '\');');
。 - Funk Forty Ninermysql_real_escape_string()
。相应的i
版本确实需要传递连接,否则它将无法工作;至少我上次知道是这样的。 - Funk Forty Niner