我如何在MySQL数据库中使用PHP插入图片?(How can I insert an image

2019-10-16 18:52发布

我使用这种形式:

<FORM action="testimage1.php" method="post">
                 <div style="font:bold 10px arial,serif;" >Product Name*</div>
                 <input type="text" name="myuserName" maxlength="50" /><br />
                  <div style="font:bold 10px arial,serif;" >Upload a photo</div>
                 <input name="uploadimage" type="file" /></br>
                 <div style="font:bold 10px arial,serif;">Product Description:</div> <input type="text" name="product" value=""></br>
                 <input id="submit" type="submit" value="submit" /><br />
                 </form>

在test1.php

require_once("dbconnect.inc.php");  //for database connection                   
    $db_name="thinstrokes";                                     
     $tbl_name="product";
     $db_selected=mysql_select_db("$db_name")or die("cannot select DB");
    // Connect to server and select databse.
    // username and password sent from form 
    $myusername=$_POST['myusername']; 
    $myproduct=$_POST['product'];
    $filename=$_POST['uploadimage'];

$imgData = file_get_contents($filename);
    $size = getimagesize($filename);
    $sql = "INSERT INTO product
    (productname, image_id , image_type ,image, image_size, image_name,productdesc)
    VALUES
    ('$myusername','11', '{$size['mime']}', '{$imgData}', '{$size[3]}', 
     '{$_FILES['userfile']['name']}','$productdesc')";
    $result=mysql_query($sql) or die("error in uploading/*");

并获得错误是: -

警告:和getimagesize(DSC02945.JPG)[function.getimagesize]:未能打开流:C中没有这样的文件或目录:\ XAMPP \ htdocs中\ thinstrokes原址\上线23 testimage1.php

我应如何修正呢.. ???

Answer 1:

你在你的窗体声明必须是enctype =的multipart / form-data的。 并通过$ _FILES变量,而不是$ _POST变量访问该文件。 喜欢:

<form action="testimage1.php" method="post" enctype="multipart/form-data">
   <input name="uploadimage" type="file" />
</form>

<?php
    $filename = $_FILES['uploadimage']['tmp_name'];   
?>


Answer 2:

$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);


文章来源: How can I insert an image in a MySQL database using PHP?