[英]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.