I am able to upload an image to mysql database using this code:
<!doctype html>
<html>
<head>
<?php
require_once 'include/db-function.php';
if(isset($_POST['upload'])){
$filename = $_POST['category_name'];
if (getimagesize ($_FILES['image']['tmp_name'] ) ==FALSE){
echo failed;
} else{
$name =addslashes( $_FILES['image']['name']);
$image = base64_encode(file_get_contents(addslashes($_FILES["image"]["tmp_name"])));
saveimage($filename, $image);
}
}
function saveimage($filename,$image){
global $connection;
$query = "insert into categories(category_name,image) values('$filename','$image')";
$result = mysqli_query($connection, $query);
if ($result){
echo "success";
}else{
echo "failed";
}
}
?>
<body>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='image' />
Enter image name :<input id="category_name"type="text" name="category_name">
<input type= "submit" value='Save name' name='upload'>
</form>
</body>
I'm then trying to fetch the data from the database to JSON array with the following:
<?php require 'include/db-connect.php';
$sql = "select * from categories";
$res = mysqli_query($connection, $sql);
$result = array();
if ($res != false) {
while ($row = mysqli_fetch_array($res)) {
array_push($result, array(
'category_id' => $row['category_id'],
'category_name' => $row['category_name'],
'image' => base64_encode($row['image'])
)
);
}
echo json_encode(array("result" => $result));
}
mysqli_close($connection);
?>
On the Android Side this is what I've done:
private void parseData(String response){
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Utils.JSON_ARRAY);
ArrayList<CategoryModel> categories = new ArrayList<>();
for (int i = 0; i < result.length(); i++) {
JSONObject data = result.getJSONObject(i);
CategoryModel categoryModel = new CategoryModel();
categoryModel.setImage(data.optString ("image"));
categoryModel.setCategoryName(data.optString("category_name"));
listCategories.add(categoryModel);
}
}
catch (JSONException e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new CategoryViewHolder(listCategories, this);
adapter.setOnItemClickListener(onItemClickListener);
//Adding adapter to RecycleView
recyclerView.setAdapter(adapter);
}
and in the onBindViewHolder This is what I have...I'm really not sure what to use to set image. You could also assist me here.
public void onBindViewHolder(CategoryViewHolder.ViewHolder holder, int
position) {
CategoryModel category = categories.get(position);
String categories = "";
holder.textView.setText(category.getCategoryName());
//holder to setImage not sure about this part
}
I'm able to get the Category Name but not able to retrieve Image. Your Help will be gladly appreciated.