[英]Upload image URL to mySQL database for JSON output
因此,我需要将图像及其URL上传到mySQL数据库。 现在,我可以正常工作,以便将图像及其相对路径上载到数据库,并将其输出为JSON,如下所示:( filepath是相对路径)
[{"name":"photo","image":"savedphoto.jpg","filepath":"uploads/savedphoto.jpg"}]
我想要的是完整的网址,如下所示:
[{"name":"photo","image":"savedphoto.jpg","filepath":"http://mywebsite.com/uploads/savedphoto.jpg"}]
这是我的代码:
$name = $_POST['new'];
$target_dir = "uploads/";
$uploadOk = 1;
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$image_name = addslashes($_FILES['image']['name']);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
$query = mysql_query("INSERT INTO new (name, filepath, image)
VALUES ('$name', '$target_file', '$image_name')");
if($query)
{
echo"Successful";
} else {
echo"Error";
}
}
是否可以将完整的URL保存到数据库? 我将如何更改代码? 我想将数据输出到JSON。
我的JSON输出文件:
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
function_exists('json_encode');
你可以更换
$query = mysql_query("INSERT INTO new (name, filepath, image)
VALUES ('$name', '$target_file', '$image_name')");
与
$query = mysql_query("INSERT INTO new (name, filepath, image)
VALUES ('{$name}', 'http://mywebsite.com/{$target_file}', '{$image_name}')");
但。 最好将其替换为输出文件
$tempArray = $row;
array_push($resultArray, $tempArray);
与
$tempArray = $row;
$tempArray->filepath = "http://{$_SERVER['HTTP_HOST']}/{$tempArray->filepath}";
array_push($resultArray, $tempArray);
之后,您的脚本将可以在任何主机上正常工作,而无需更改数据库中的数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.