1

I am unable to upload the second image until I've removed the first image from MySQL using PHP. When I upload the image, the message shown is "image not uploaded". This message is shown until I remove the image from the MySQL database.

My Code:

<?php 
ini_set('mysql.connect_timeout',300);
ini_set('default_socket_timeout',300);
?>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<br/>
    <input type="file" name="image"/>
    <br/><br/>
<input type="submit" name="submit" value ="Upload"/> 
</form>
<?php 
if(isset($_POST['submit'])) {
    if(getimagesize($_FILES['image']['tmp_name'])== FALSE) {
        echo "Please Select an image" ;
    }
    else {
        $image =addslashes($_FILES['image']['tmp_name']);
         $name =addslashes($_FILES['image']['name']);
        $image= file_get_contents($image);
        $image= base64_encode($image);
        saveimage($name,$image);
    }
}
displayimage();
function saveimage($name,$image) {
  $con=mysqli_connect("localhost","***","***");


    mysqli_select_db($con,'images');
    $qry="insert into images(name,image) values ('$name','$image')";
    $result=mysqli_query($con,$qry);
    if($result){
        echo "<br/> Image uploaded.";
    } else {
        echo "<br/> Image not uploaded.";
    }
}
function displayimage ()
{
    $con=mysqli_connect("localhost","***","***");
    mysqli_select_db($con,"images");
    $qry="select * from images";
    $result=mysqli_query($con , $qry);
    while ($row = mysqli_fetch_array($result)) {
        echo '<img height="300" width="300" src = "data:image;base64,'.$row[2].'">';
    }
    mysqli_close($con);
}

?>

Kitson88
  • 2,889
  • 5
  • 22
  • 37
Ahmed
  • 35
  • 1
  • 7
  • **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use string interpolation or concatenation to accomplish this because you have created a severe [SQL injection bug](http://bobby-tables.com/). **NEVER** put `$_POST` or `$_GET` data directly into a query, it can be very harmful if someone seeks to exploit your mistake. `addslashes` is **NOT** a substitute for proper escaping. – tadman Dec 07 '16 at 20:44
  • Output a useful error message. After `echo "
    Image not uploaded.";` add a line like this `echo mysqli_error($con); exit;` Then the system will tell you what you have done wrong
    – RiggsFolly Dec 07 '16 at 20:45
  • Add [error reporting](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php/845025#845025) to the top of your file(s) _while testing_ right after your opening PHP tag for example ` – RiggsFolly Dec 07 '16 at 20:46

0 Answers0