如何用PHP将图像上传到我的mysql数据库?

时间:2017-07-04 09:36:15

标签: php mysql server upload

我知道我应该使用LONGBLOB,到目前为止我已编写此代码,将文本上传到我的服务器。如何上传图片而不是文字?。

//if(isset...)
$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$t = $_POST['tekst'];

$sqlScript = "INSERT INTO form (tekst) VALUES ('$t')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);

它应该保存mysql数据库的路径。图像应存储在服务器的计算机上。

2 个答案:

答案 0 :(得分:0)

您不需要将图像直接存储到数据库中。只需将图像名称存储在数据库中,然后在要显示时获取它。 例如,

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// 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;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        // execute your insert query here
       $sqlScript = "INSERT INTO form (image) VALUES ('".basename( $_FILES["fileToUpload"]["name"])."')";


    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

答案 1 :(得分:-1)

替代方案:在base64中转换图像并保存文本。

$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$image_string = base64_encode(file_get_contents($myimage));

$sqlScript = "INSERT INTO form (images) VALUES ('$image_string')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);