【发布时间】:2015-08-11 13:48:28
【问题描述】:
我正在开发一个应用程序,它通过 HttpConnection 将 JSON 发送到 PHP 服务器,我的脚本在插入到 MYSQL 数据库之前接收并解码它,尽管它已将图像转换为 base64,我确信我正在做很多出了问题,特别是当我在 foreach 中进行查询时,实际上这现在不起作用,所以请你帮我解决这个问题,也许能找到更好的方法来执行?
我已经测试了创建 JSON 对象的应用程序脚本,这很好。我的问题只是 PHP JSON 解码和 MYSQL 插入查询(Mysql 脚本连接也可以)。
谢谢你帮助我。
require('mysqli.php');
if(strcmp('send-json', $_POST['method']) == 0){
$MySQLi = new MySQLi($MySQL['servidor'], $MySQL['usuario'], $MySQL['senha'], $MySQL['banco']);
$MySQLi->set_charset('utf8');
$relatorio = utf8_encode($_POST['json']);
$relatorio = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $relatorio);
$relatorio = json_decode($relatorio);
$i = 0;
foreach ( $relatorio as $r ){
if($r->{'img-antes'} != ""){
$binary = base64_decode($r->{'img-antes'});
$file_antes = fopen('img/'.$r->{'id'}.'_FOTO_ANTES.jpg','wb');
fwrite($file_antes, $binary);
fclose($file_antes);
$url_antes="img/".$r->{'id'}."_FOTO_ANTES.jpg";
}else{
$url_antes="";
}
if($r->{'img-depois'} != ""){
$binary = base64_decode($r->{'img-depois'});
$file_depois = fopen('img/'.$r->{'id'}.'_FOTO_DEPOIS.jpg','wb');
fwrite($file_depois, $binary);
fclose($file_depois);
$url_depois="img/".$r->{'id'}."_FOTO_DEPOIS.jpg";
}else{
$url_depois="";
}
$insert = "INSERT INTO Relatorio (id,Latitude,Longitude,URL_Antes,URL_Depois)
VALUES ('".$r->{'id'}."',
'".$r->{'Latitude'}."',
'".$r->{'Latitude'}."',
'".$url_antes."',
'".$url_depois."')";
$send = $MySQLi->query($insert) OR trigger_error($MySQLi->error, E_USER_ERROR);
if($send){$i++;}
//$send->free();
}//fim do LOOP
if($i > 0){
echo '1';//This a Good Answer to send back to my Application
}
else{
echo '2';//This a Bad Answer to send back to my Application
}
这是我的 JSON,没有图像 Base64 数据。请在此站点中添加一个:http://www.base64-image.de/ 只是为了测试它。
{
"relatorio":[
{
"id":"F001EVLA366666LO129999",
"Longitude":"21.61312634634566",
"Latitude":"36.6623457906766",
"img-antes":"please include an imageBASE64 here",
"img-depois":""
}
{
"id":"F001EVLA468888LO129888",
"Longitude":"55.65623213165487",
"Latitude":"23.95626265922322",
"img-antes":"please include an imageBASE64 here",
"img-depois":"please include an imageBASE64 here"
}
]
}
【问题讨论】:
-
不要使用 utf 编码和 preg_replace 破坏 json。您可能会引入语法错误,使 json 无效并且解码失败。你很容易受到sql injection attacks
标签: php android mysql json base64