duandeng2011 2015-07-29 17:13
浏览 31
已采纳

将图像URL上载到mySQL数据库以获取JSON输出

So I need to upload images and their URLs to a mySQL database. Right now I have it working so that an image and its relative path is being uploaded to the database and I am outputting it to JSON like so: (filepath is the relative path)

[{"name":"photo","image":"savedphoto.jpg","filepath":"uploads/savedphoto.jpg"}]

What I want is the full URL like so:

[{"name":"photo","image":"savedphoto.jpg","filepath":"http://mywebsite.com/uploads/savedphoto.jpg"}]

Here is the code I have:

$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";
    }
}

Is it possible to save the full URL to the database? How would I alter the code? I want to output the data to JSON.

My JSON output file:

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');
  • 写回答

1条回答 默认 最新

  • dongpao1921 2015-07-29 17:18
    关注

    u can replace

    $query = mysql_query("INSERT INTO new (name, filepath, image)
            VALUES ('$name', '$target_file', '$image_name')");
    

    with

    $query = mysql_query("INSERT INTO new (name, filepath, image)
                VALUES ('{$name}', 'http://mywebsite.com/{$target_file}', '{$image_name}')");
    

    BUT. its better to replace in you output file

    $tempArray = $row;
    array_push($resultArray, $tempArray);
    

    with

    $tempArray = $row;
    $tempArray->filepath = "http://{$_SERVER['HTTP_HOST']}/{$tempArray->filepath}";
    array_push($resultArray, $tempArray);
    

    after that your script will work on any host properly without changing data in database

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算