上传将PHP变量读为null

时间:2015-06-28 08:10:17

标签: php html mysql

我无法从mysql数据库加载图片。该目录是随机生成的,并且可以很好地存储在数据库中。当页面刷新时,img返回一个断开的链接,回声'未设置',并且inspect元素告诉我$ default_pic未定义。我无法弄清楚这里有什么可以帮到谁?

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$listingid = $_SESSION['edit_listing'];
if(isset($_FILES['listingpic'])){
    if($_FILES['listingpic']['type']=="image/jpeg"||$_FILES['listingpic']['type']=="image/png"||$_FILES['listingpic']['type']=="image/gif"){
        if($_FILES['listingpic']['size']<1048576){
            $chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            $rand_dir_name = substr (str_shuffle($chars), 0, 15);
                                    mkdir("userdata/listingpics/$rand_dir_name/") or die("directory error");
            if(file_exists("userdata/listingpics/$rand_dir_name/".$_FILES['listingpic']['name'])){
                echo "File already exists.";
            }
            else{
                move_uploaded_file($_FILES['listingpic']['tmp_name'], "userdata/listingpics/$rand_dir_name/".$_FILES['listingpic']['name']) or die("Failed to move file.");
                $listing_pic_name = $_FILES['listingpic']['name'];
                $listing_pic_query = mysql_query("UPDATE properties SET default_pic='$rand_dir_name/$listing_pic_name' WHERE id='$listingid'"); 
                $check_def = mysql_query("SELECT default_pic FROM properties WHERE id='$listing_id'"); //ADDED
                $def_rows = mysql_fetch_assoc($check_def); //ADDED
                $def_pic = $def_rows['default_pic']; //ADDED
                $default_pic = "userdata/listingpics/".$def_pic;//<-PROBLEM
                header("Location: ../list_property/upload.php?id=".$listingid);
            }
        } else echo "File must not exceed 1MB.";
    } else echo "File must be a JPEG, PNG, or GIF image.";
} else echo "Not set.";

?>
<form action="" method="POST" enctype="multipart/form-data">
    <img src="<?php echo $default_pic; ?>" width="50%" height="50%"/><br>
    <br>
    <input type="file" name="listingpic" />
    <input type="submit" name="uploadpic" value="Upload Picture">
</form>

1 个答案:

答案 0 :(得分:2)

当您上传图片后刷新页面时,脚本会刷新,这意味着您的$default_pic会重置,因此它会变空。

如果你不想摆脱那个错误,你应该编写一个查询,从数据库中提取默认图像并填写变量。