Skip to content
Advertisement

How to insert the image file in mysql table?

I need to insert the image into MySQL table. The HTML code is,

<form action="" method="POST" enctype="multipart/form-data" >
            <label for="My photo" style="color: brown; font-size: 15px; margin-left: 10px"> My Avatar</label>    
            <div class="row">
            
            <div class="col l5">    
            <input type="file" class="form-control"  name="myfile" id="myfile" style="margin-left: 10px; " placeholder="My Photo">
            </div>    
            <div class="col l4">
            <button type="submit" id="insert" style=" height: 40px; color: brown">Insert Image</button>
            </div>
            
            </div>        
            </form>

and php code is,

<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["insert"])){    
   $file = addslashes(file_get_contents($_FILES["myfile"]["tmp_name"]));
  $sql = "INSERT INTO insertimage(MyPhoto)
VALUES ('$file')";
    
if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
} 
}
$conn->close();
?>

After the connection to MySQL is successful, it is not inserting into the table. Can you fix this error?

Advertisement

Answer

change this

<button type="submit" id="insert" style=" height: 40px; color: brown">Insert Image</button>

to and add attribute name="insert"

<button type="submit" id="insert"  name="insert" style=" height: 40px; color: brown">Insert Image</button>

Note:- For inserting <form> data in database you need to add name attribute.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement