所以我需要将图像及其 URL 上传到 mySQL 数据库。现在我可以正常工作,以便将图像及其相对路径上传到数据库,并将其输出到 JSON,如下所示:(filepath 是相对路径)
[{"name":"photo","image":"savedphoto.jpg","filepath":"uploads/savedphoto.jpg"}]
我想要的是完整的 URL,如下所示:
[{"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);
之后您的脚本将在任何主机上正常运行,而无需更改数据库中的数据
关于php - 将图像 URL 上传到 mySQL 数据库以进行 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706997/