inserting image into mysqli database using PHP

 Before running this code create table using phpmyadmin or using below code ($table) to create table,

<html>

<form method="post" action = "" enctype="multipart/form-data">

<input type="file" name="img">

<br>

<input type="submit" name="submit">

</form>

</html> 

<?php

$conn = mysqli_connect("localhost","root","","learn");

if(!$conn)

{

    echo "db not connected ";

}

$table = "CREATE TABLE photos (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(30) NOT NULL,

filename blob NOT NULL,

)";

mysqli_query($conn,$table);

if(isset($_POST['submit']))

{

    $image = $_FILES['img']['tmp_name'];

    $name = $_FILES['img']['name'];

    $image = file_get_contents($image);

    $image = base64_encode($image);

    $sql = "INSERT INTO photos (name,filename) VALUES ('$name','$image')";

    mysqli_query($conn,$sql);

    echo " file uploaded";

}

else{

    echo "photo not uploaded";

}

$sqm = "select * from photos";

$result  = mysqli_query($conn,$sqm);

if(mysqli_num_rows($result)>0)

{

    while($row = mysqli_fetch_array($result))

    {

     echo "<br>";

     echo '<img src= "data:image;base64,'.$row['filename'].' ">'."<br>";

}

?>

Comments