php - 将图像 URL 上传到 mySQL 数据库以进行 JSON 输出

标签 php mysql json database url

所以我需要将图像及其 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/

相关文章:

php - 在 jpGraph 的数据库显示中需要换行符

php - 阻止用户与多个 IP 共享帐户?

mysql - 清理 MySQL 表的表单数据

javascript - 如何使用nodejs获取异步数据

java - 文件类中的新 BufferedReader 无法应用于给定类型

php - php 中下拉框中选项标签的 while 循环不起作用

php - 查看结果在哪个表中

php - Laravel 5 - Paypal 支付 - 将数据表单传递给 Controller

javascript - 解析 JSON 数据并获取一个对象

android - Volley 发送 POST 参数始终为空