简体   繁体   English

如何在php中将图像上传到数据库?

[英]How to upload image to database in php?

here i am trying to upload image to directory and add the path in database. 在这里,我试图将图像上传到目录并在数据库中添加路径。 here i am first adding some product details and trying to upload the image to uploads directory and add the uploaded image path in database. 在这里,我首先添加一些产品详细信息,然后尝试将图像上传到uploads目录,并在数据库中添加上传的图像路径。

here is what i have done: 这是我所做的:

   <?php
    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    $link = mysqli_connect("localhost", "root", "", "wan_products_box");

    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Escape user inputs for security
    $product_name = mysqli_real_escape_string($link, $_POST['product_name']);
    $product_category = mysqli_real_escape_string($link, $_POST['product_category']);
    $product_price = mysqli_real_escape_string($link, $_POST['product_price']);
    $pro_url = mysqli_real_escape_string($link, $_POST['pro_url']);
    $co_owners = mysqli_real_escape_string($link, $_POST['co_owners']);


    // attempt insert query execution
    $sql = "INSERT INTO product_list (product_name, product_category, product_price,product_referrence_URL,product_co_owners) VALUES ('$product_name', '$product_category', '$product_price', '$pro_url', '$co_owners')";
    if(mysqli_query($link, $sql)){
        echo "New product created.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }

    //image upload code

    if($_POST)
    { 
    if($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
    else
    {
    if(file_exists("uploaded_images/" . $_FILES["file"]["name"]))
    {
    echo $_FILES["file"]["name"] . " already exists. ";
    }
    else
    {  
    if(move_uploaded_file($_FILES["file"]["tmp_name"],"uploaded_images/" . $_FILES["file"]["name"]))
    {
    $query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
    if(mysql_query($query_image))
    {
    echo "Stored in: " . "uploaded_images/" . $_FILES["file"]["name"];
    }
    else
    {
    echo 'Unable to store';
    }
    }
    }
    }
    }
    mysqli_close($link);
    ?>

this is my html form: 这是我的html形式:

<div id="menu2" class="tab-pane fade">
      <h4>Add new product</h4>
      <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
      <div class="panel panel-default">
      <div class="panel-body">        


            <form class="form-horizontal" method="post" action="files/insert.php" role="form">
              <div class="form-group">
                <label class="control-label col-sm-2" for="product_name">Product Name</label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" name="product_name" id="product_name" placeholder="Iphone 5c" required>
                </div>
              </div>

              <div class="form-group">
                <label class="control-label col-sm-2" for="pwd">Product Category</label>
                <div class="col-sm-10">                            
                  <select class="btn-btn-primary form-control" name="product_category">
                    <option>Mobile</option>
                    <option>Television</option>
                    <option>Printer</option>
                    <option>Watch</option>
                    <option>Monitor</option>
                  </select>
                </div>
              </div>

              <div class="form-group">
                <label class="control-label col-sm-2" for="product-pic">Upload your profile picture</label>
                <div class="col-sm-10">          
                  <input type="file" class="form-control" name="file" id="file" /> 
                </div>
              </div>


              <div class="form-group">
                <label class="control-label col-sm-2" for="product_price">Product Price</label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" name="product_price" id="product_price" placeholder="Rs.36,000" required>
                </div>
              </div>


              <div class="form-group">
                <label class="control-label col-sm-2" for="pro_url">Reference URL</label>
                <div class="col-sm-10">
                  <input type="URL" class="form-control" name="pro_url" id="pro_url" placeholder="http://www.amazon.com" required>
                </div>
              </div>


              <div class="form-group">
                <label class="control-label col-sm-2" for="co_owners">Co-owners</label>
                <div class="col-sm-10">
                    <select class="btn-btn-primary form-control" name="co_owners">
                        <option>Select no. owners</option>
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                        <option>5</option>
                        <option>6</option>
                        <option>7</option>
                        <option>8</option>
                        <option>9</option>
                        <option>10</option>
                        <option>11</option>
                        <option>12</option>
                        <option>13</option>
                        <option>14</option>
                        <option>15</option>
                    </select>                      
                </div>
              </div>


              <div class="form-group">        
                <div class="col-sm-offset-2 col-sm-10">
                  <button type="submit" class="btn btn-success">Add product</button>
                </div>
              </div>
            </form>


      </div>
      </div>
      </div>    
    </div>

the data is inserted to database but the image upload part is not happening... how can i do this? 数据已插入数据库,但图像上传部分未发生...我该怎么做? how can i modify the code to upload the image to database and add path to database? 如何修改代码以将图像上传到数据库并添加数据库路径?

when i run this the output i get is 当我运行此输出时,我得到的是

New product created.
Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 31

Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 37

Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line 43

Notice: Undefined index: file in D:\xampp\htdocs\wan\files\insert.php on line

There are a few things wrong in your code. 您的代码中有些错误。

Firstly, your form is missing a valid enctype enctype="multipart/form-data" it is required when dealing with files. 首先,您的表单缺少处理文件时需要的有效enctype enctype="multipart/form-data"

You're also mixing MySQL APIs in your second query. 您还将在第二个查询中混合使用MySQL API。

$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";
if(mysql_query($query_image))
  • So it will fail. 因此它将失败。

Use the same method you used in your first query. 使用您在第一个查询中使用的相同方法。

  • Those different APIs do not intermix. 这些不同的API不会相互混合。

So change that to if(mysqli_query($link, $query_image)) 因此将其更改为if(mysqli_query($link, $query_image))

Also add or die(mysqli_error($link)) to mysqli_query() to check for errors. 还要在mysqli_query()添加or die(mysqli_error($link)) mysqli_query()以检查错误。

Also make sure the folder has proper permissions to be written to. 还要确保该文件夹具有适当的写入权限。

Another thing, your <select> 's options have no values 另一件事,您的<select>选项没有值

<option>Select no. owners</option>
<option>1</option>
...

You need to add those 您需要添加那些

<option value="empty_value">Select no. owners</option>
<option value="1">1</option>
...

and do the same for the others. 并为其他人做同样的事情。

Same thing for <option>Mobile</option> . <option>Mobile</option> There should be values for those too. 这些也应该有价值。

<option value="mobile">Mobile</option>
...

You will not get anything entered in your database for those. 您将不会在数据库中输入任何内容。

Apart from the problems in HTML part like the lack of enctype="multipart/form-data" . 除了HTML部分的问题外,例如缺少enctype="multipart/form-data" There is a problem in your second Query and this is the cause of these errors: 您的第二个查询中有一个问题,这是这些错误的原因:

$query_image = "INSERT INTO product_list (product_image_url) values ('".$_FILES['file']['name']."')";

You need to change this to an UPDATE query and update the already created row in database. 您需要将此更改为UPDATE查询,并更新数据库中已创建的行。

Also it is a better approach to use the row's index number for the image name. 同样,将行的索引号用作图像名称也是一种更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM