I am developing an Android application that allows user to upload images from their Android to the a 000webhost server, by referring to this link, I had managed to successfully send the image to the web server (file manager?).
However, I'd like to send the image to the database of the server instead, but I had been facing issue inserting the image into the database, below is the PHP code I am using:
<?php
include 'connection.php';
$con = mysqli_connect($hostname_localhost, $username_localhost, $password_localhost, $database_localhost);
if (mysqli_connect_error()){
echo 'Error: Connection failed.';
exit();
}
// Get image string posted from Android App
$base=$_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$sql = "INSERT INTO images (bitmap, name) VALUES ('$binary', '$filename')";
//mysqli_query($con, $sql)
if ($con->query($sql) === TRUE) {
echo 'Success';
} else {
// Images will be saved under 'upload' folder
$file = fopen('upload/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';
}
mysqli_close($con);
?>
My database named images has 3 columns:
id INT(100) AUTO_INCREMENT PRIMARY KEY
bitmap TEXT
name VARCHAR(100)
I tried passing just the filename into the database earlier and it worked, so I am suspecting the data type for bitmap is wrong.
Or should I, instead of passing the image into the database, keep the path of the image in the web server instead?
EDIT: I got rid of the if else statement and only saved the filename into the database, the image is saved to the server. For retrieval, I defined the path to the folder where images are being kept at, and used readfile() to send the image back to Android, using HTTPUrlConnection from here.