George Young George Young - 3 months ago 23
HTML Question

Uploading image to mysql using html and php

I am trying to upload a image from my html form to my mysql blob column.
I feel like the php file isn't receiving the file based off of all the testing to try to figure out what is not working.

relevant HTML code:

<form action = "insert.php" method="post" enctype="multipart/form-data">
<input type="file" name="myimage">
<input type="submit" name = "Insert" value="Insert">
</form>


relevant PHP code:

$imagename=$_FILES["myimage"]["name"];

if(getimagesize($FILES['myimage']['tmp_name']) == FALSE){
echo "no image";
}
//Get the content of the image and then add slashes to it
$imagetmp = addslashes($_FILES['myimage']['tmp_name']);
$image = file_get_contents($imagetmp);
$sql = "INSERT INTO locations (image) VALUES ('$image')";
$res = mysql_query($sql) or die(mysql_error());


I believe the php isn't recieving the file because I always get my "no image" echoed.

Answer

Before inserting into the database I think you should base64_encode the data.

$imagename=$_FILES["myimage"]["name"];
if( getimagesize( $FILES['myimage']['tmp_name'] ) == FALSE ){
    exit( "no image" );
}

$image = base64_encode( file_get_contents( $_FILES['myimage']['tmp_name'] ) );

To use mysqli you could do something like:

$servername = "localhost";
$username = "foo";
$password = "xxx";
$dbname = "bar";

$db=new mysqli( $servername, $username, $password, $dbname );

$sql='insert into `locations` set `image`=?';
$stmt=$db->prepare( $sql );

$stmt->bind_param( 's', $image );
if( $stmt ) $stmt->execute();

$db->close();

$sql = "INSERT INTO `locations` (`image`) VALUES ('$image')";
$res = mysql_query( $sql ) or die( mysql_error() );
Comments