【发布时间】:2019-04-17 12:43:41
【问题描述】:
我有一个 Android 应用程序,它拍摄照片、将位图转换为 Base64 并将 Base64 字符串提交到 MySQL 数据库(通过 PHP)以存储为 longblob。这部分效果很好!事实上,我可以从 phpMyAdmin 下载 longblob 作为完美的 Base64 字符串并轻松转换为 JPEG 照片。
问题是我获取 blob 的 PHP 代码返回一个空字符串:
{
"owner":"Unknown",
"pet_name":"Unknown",
"last_seen":"2019-04-09 11:17:19",
"contact":"999-888-7654",
"description":"rubber ducky, lotsa fun",
***"photo":""***,
"location":"Some location"
}
PHP 吸气剂:
function getReports() {
$stmt = $this->con->prepare("SELECT owner, pet_name, last_seen, contact, description, photo, location FROM Pets");
$stmt->execute();
$stmt->bind_result($owner, $pet_name, $last_seen, $contact, $description, $photo, $location);
$reports = array();
while($stmt->fetch()) {
$report = array();
$report['owner'] = $owner;
$report['pet_name'] = $pet_name;
$report['last_seen'] = $last_seen;
$report['contact'] = $contact;
$report['description'] = $description;
$report['photo'] = $photo;
$report['location'] = $location;
array_push($reports, $report);
}
return $reports;
}
一个有趣的附注,如果我使用下面的代码而不是上面的代码,我会得到完整的 Base64 字符串,但在整个过程中都添加了转义 () 和换行符 (\n):
//Select everything from table
$sql= "SELECT * FROM Pets";
//Confirm results
if($result = mysqli_query($con, $sql)) {
//Results? Create array for results and array for data
$resultArray = array();
$tempArray = array();
//Loop through results
while($row=$result->fetch_object()) {
// Add each result in results array
$tempArray=$row;
array_push($resultArray,$tempArray);
}
//Encode array to JSON and output results
echo json_encode($resultArray);
}
我想找到一种方法来修复上述 PHP 代码。我在想也许我的字符串对于$photo 值来说太长了?任何建议将不胜感激。
更新:从Selecting Blob from MYSQL, getting null 我确实设法使用 Base64 现在输出而不是空字符串。但是,我仍然遇到转义和换行符的问题。
这里有什么帮助吗?
【问题讨论】:
-
注意:object-oriented interface to
mysqli明显不那么冗长,使代码更易于阅读和审核,并且不容易与过时的mysql_query接口混淆,因为缺少单个i会导致麻烦。示例:$db = new mysqli(…)和$db->prepare("…")过程接口很大程度上是 PHP 4 时代引入mysqliAPI 时的产物,不应在新代码中使用。 -
更新问题。我确实想出了如何让base64输出而不是空的“”。但是,它仍然包含转义符和换行符。
-
将图像放入数据库通常是一个糟糕的计划,它需要多层编码和解码才能将其从数据库中取出并通过网络发送,而 base64 编码只能使事情更差。为什么不生?
-
it still contains the escape and newline chars- 很可能是因为您首先将它以那种形式放入数据库中。 -
Base64 不适用于存储。您可能想阅读Storing image in database directly or as base64 data?