Modifying the background-image to an SQL image

Can the

background-image: url(--SET THIS--)
be set to an SQL picture? I am considering something like this:

$img = $MysqliHandler->query(SELECT  avatar FROM account WHERE username="'.$_SESSION['name'].'"';

And then somehow change the URL to:

'.base64_encode( $img[0]['avatar'] ).'

Currently, I only have a simple change avatar function, but I want to save this to a specific "'.$_SESSION['name'].'", so that the user always has that avatar and can change it. Should I use ajax, link the new image to another PHP file, and run an update image SQL function there?

$("#ChangeImg").click(function(e) {
  $("#imageUpload").click();
});

function fasterPreview(uploader) {
  if (uploader.files && uploader.files[0]) {
  var reader = new FileReader();
  reader.readAsDataURL(uploader.files[0]);
  reader.onloadend = function(){
    document.getElementById("imgDivEdit").style.backgroundImage = "url(" + reader.result + ")";  
   }
  }
}
$("#imageUpload").change(function() {
  fasterPreview(this);
});
#imageUpload {
  display: none;
}

.container {
  position: relative;
  width: 125px;
  height: 125px;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 125px;
  width: 125px;
  opacity: 0;
  transition: .5s ease;
  background-color: rgba(11, 90, 180, 0.795);
  border-radius: 50%;
}

.container:hover .overlay {
  opacity: 0.7;
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  text-align: center;
  cursor: pointer;
}

#imgDivEdit {
  width: 125px;
  height: 125px;
  background-image: url("https://www.whatsappprofiledpimages.com/wp-content/uploads/2019/01/Nice-Whatsapp-DP-Profile-Images-4-300x300.jpg");
  background-position: 5px -5px;
  border-radius: 50%;
  background-size: cover;
}
<div id="avatar"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div id="imgDivEdit"></div>
  <div id="ChangeImg" class="overlay">
    <div class="text">Change Image</div>
  </div>
</div>
</div>
<input id="imageUpload" type="file" name="profile_photo" placeholder="Photo" required="" capture>

Answer №1

Utilizing

data:image/jpeg;base64,'.$_SESSION['avatar'].'
as a background in a separate .php file is how I approached this issue, all of which is naturally included in my main .php file:

#imgDivEdit{
    width: 125px;
    height: 125px;
    background-image: url("data:image/jpeg;base64,'.$_SESSION['avatar'].'");
    border-radius: 50%;
    background-size: cover;
}

I then implemented an if statement that updates the SQL data and subsequently retrieves it to update the session.

$URL = $_SERVER['REQUEST_URI'];
if(isset($_POST['Save']) && !empty($_POST['Save']))
{
    if($_FILES["imageUpload"]["size"] > 1010000 || $_FILES["imageUpload"]["size"]==0 )
    {
            echo"<h3 style='color:#db4409'>Failed to upload image.</h3>";
    }
    else{            
            $image=addslashes(file_get_contents($_FILES['imageUpload']['tmp_name']));
            $sql='UPDATE accounts SET avatar = ("'.$image.'") WHERE username ='.$_SESSION['name'].'';
            $query = $MysqliHandler->query($sql);
            $sql='SELECT avatar FROM accounts WHERE username ='.$_SESSION['name'].'';
            $avatar = $MysqliHandler->query($sql);
            $_SESSION['avatar'] = base64_encode( $avatar[0]['avatar'] );
            header("Refresh:0; url=$URL");
            exit();                             
    }
}

A save option was created to trigger all these actions when an image is uploaded, with the following displayed:

<form method="POST" enctype="multipart/form-data">                           
    <input id="imageUpload" type="file" name="imageUpload" placeholder="Photo" accept="image/x-png,image/gif,image/jpeg" required="" capture>
    <div id="Change" hidden>
        <input  type="submit" name="Save" id="Save" value="Save" class="btn btn-info Save"/> <p style="font-size:11px;">Max size: 1Mb</p>
    </div>
</form>

.js

$("#imageUpload").change(function() {
    $("#Change").show();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for calculating the product of a 4x4 Matrix with a vector-array of any size?

When creating a specific scene in webgl, the usual process of transforming an object involves defining the initial vertex position data and sending it to the vertex shader. In the shader, the vertices are manipulated by various matrices that contain inform ...

What is the best way to turn off autocorrect in a textarea on IE11 without turning off spellcheck?

In my experience, disabling the spellcheck attribute seems to solve the auto-correct issue, but it also eliminates the underlining of misspelled words. <textarea id="TextArea1" spellcheck="false"></textarea> I prefer to keep spellcheck enabl ...

What causes the map function to behave differently when I use an array as the return value rather than a primitive in the callback function?

Program var corporations=[ {name:'Vicky',category:'Devdas',start:1993,end:2090}, {name:'Vikrant',category:'Devdas',start:1994,end:2019}, {name:'Akriti',category:'mental',start:1991,end:2021}, { ...

I'm experiencing a problem when trying to add a document to Firebase Firestore using React Native - it doesn't seem to

I'm currently working on a React Native project that utilizes Firebase v9. My goal is to add a user object to my user collection whenever a new user signs up through the sign-up screen. However, I've encountered an issue where the user object is ...

Transfer information from one input field to another and then proceed to submit the form

I need to move the content of an input field that is located higher up the page to a form field at the bottom of the page and then submit the form. Below is what I have attempted so far, but it is not working: $('#move_down').click(function() ...

displaying 'undefined' upon completion of iterating through a JSON file using $.each

For my project, I am attempting to extract only the date data from a JSON object. I have successfully looped through the object and displayed it, but the issue arises at the end of the loop where it shows undefined. I am not sure what mistake I am making. ...

Animate a CSS transition to smoothly slide a hidden div into view from the edge to the center of the

I am looking to create an animated floating div. When the div is in the 'closed' state, most of it is hidden on the right side of the screen, with only 20px still visible. Upon clicking the visible part, I want the div to move to the center of t ...

Angular directive loads after receiving variables

In my project, there is an Angular directive responsible for loading data from a service. However, the data is being loaded using a variable obtained from a controller, which in turn was loaded from a service. Below is the code snippet for the directive: ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

Is there a way to display the description field instead of the Id in a table using pxp-ui?

I am currently working with a table in pxp-ui and have implemented the following column: subsystemId: { type: 'AutoComplete', isSearchable: true, label: 'Subsystem Id', ...

Extracting data from nested objects array in React: A step-by-step guide

I am facing an interesting challenge. Currently, I am immersing myself in learning react and have managed to retrieve data from a demo API that I created using Java Spring. Although I am successfully receiving the data in React, my struggle lies in creati ...

Combining CSS, jQuery, and HTML into a single .html file would allow for seamless integration

I've been searching extensively, but I haven't been able to locate exactly what I need. My goal is to merge my jQuery and CSS into a single .html file, but I'm struggling to get the jQuery functionality to work. Although I have experience wi ...

I'm looking to integrate Jest in my React project with npm. How can I achieve

I've developed my application with create react app and npm. While reviewing the official documentation for jest at https://jestjs.io/docs/tutorial-react, I noticed that they only provide information on testing CRA apps using yarn. Does this suggest t ...

What is the proper way to transfer data to PHP using AJAX?

I'm facing an issue while trying to send FormData to a PHP file. When I press submit, nothing happens. However, when I send data separately, it works fine. <form method="post" class="code_form" enctype="multipart/form-data& ...

What is the best way to replicate touch functionality on mobile browsers for both Android and iPhone devices?

Recently, while developing a web application, I ran into an issue on mobile browsers where the :active pseudo class wasn't functioning properly. I am currently utilizing CSS sprites and looking for guidance on how to simulate clicks for mobile browser ...

Maintaining scope integrity in an Angular application with components, including a dialog that utilizes a custom directive

I'm struggling with passing scope to a template rendered from a directive. It seems like it should be simple, but I can't seem to get it to work properly. Here is a simplified version of my HTML: <div ng-app="myApp"> <md-content> ...

Navigating using Javascript library in Angular 2 framework

I am currently utilizing Parse, an external JS library, within Angular JS 2. Nevertheless, I am encountering issues when attempting to call the function gotoMain() from within a callback function of Parse. It appears that certain elements are not being l ...

Tips for transferring variables as arguments in javascript

Currently, I am immersed in a test project aimed at expanding my knowledge of web development. Unexpectedly, I have encountered an issue that has left me puzzled on how to proceed. Within this project, there exists a table consisting of 11 cells. While 9 ...

How to style a sublevel menu to appear next to its parent using CSS

I have a menu that is currently functioning well, but I would like to add a new sublevel onto it. However, if I directly add the new options, they end up hiding the existing ones on the menu. Here's an image for reference: I want the new options to ...

Is it possible to combine EJS compilation and html-loader in the html-webpack-plugin?

I need the html-webpack-plugin to generate my html using my .ejs template that contains <img> tags. The html-loader can update the image URLs in my <img> tags created by Webpack, so I am including it in my configuration: test: /& ...