Viewed   101 times

My client have created a script in php+mysql that saves images directly in the database and every images has url like this:

In your opinion this is a very wrong solution ? Should I rebuild all the site ?

There are about 1000 visits per day and about 600 images in the database.



Images files are files, unless there is compelling reason to store them in the database, the place they belong is the file system, where you get benefits like easy backup and replication, distributed across multiple machines, directly served by the webserver, and all the last-modified-date and etag supported by the webserver to achieve better performance, etc.

if the number of images is expected to grow, and different sizes of one image are expected to be created (e.g. thumbnail images etc.) in the coming release, a plan to migrate images from db to file system is strongly suggested.

Saturday, August 27, 2022

Here's a script I modified to work with your table structure.

function addImageToDB($imageArray, $title = '', $subject = '', $visible = 0) {

$allowedExts = array("gif","jpeg","jpg","JPG","png","PNG");
$extension = end(explode(".", $imageArray["name"]));

if (
    (($imageArray["type"] == "image/gif") // is image type acceptable?
        || ($imageArray["type"] == "image/jpeg")
        || ($imageArray["type"] == "image/jpg")
        || ($imageArray["type"] == "image/png")
    && ($imageArray["size"] < 1048576) // set maximum image size
    && in_array($extension, $allowedExts) // is image file extension in $allowedExts?
) {

    if ($imageArray["error"] > 0) { // check uploaded image for errors
        echo $imageArray['error'];
    } else {

        $tempImage = $imageArray['tmp_name'];
        $fp = fopen($tempImage, 'r');
        $image = fread($fp, filesize($tempImage));
        $image = addslashes($image);

        $queryAddImageToDB = "INSERT INTO image (
        ) VALUES (

        mysql_query ($queryAddImageToDB) or die ('queryAddImageToDB failed');
        $imageID = mysql_insert_id();

        return $imageID;

} else {

    echo 'IMAGE UPLOAD ERROR: The image ie either too large or the file format is unacceptable.';

    echo '<pre>';
        print_r($imageArray); // display image array for debugging
    echo '</pre>';



You can call the function like this:

$imageArray = $_FILES['image'];
$title = $_POST['title'];
$subject = $_POST['subject'];
$visible = 1;
addImageToDB($imageArray, $title, $subject, $visible);

Please note that this script IS NOT COMPLETE as it needs proper validation, escaping, etc.

Good luck I hope this works out for you and I look forward to hearing feedback otherwise.

Monday, September 19, 2022

You only want to store the relative path, not the absolute path, as linking to something like

 <img src="/var/www/vhosts/"> 

would return a 404 on any real website. store your files in the database via a relative path (/images/file.jpg) or by only the filename if they are all in the same directory.

alternatively, you can learn MongoDB and it allows you to actually store files in the database itself.

Monday, October 31, 2022

The ideal and good way to use cart is keep it in session, codeigniter's cart class is doing the same thing, and when user gives order use this data put this order in database and do other stuff like payment gateway, shipping. If you want to use user to keep his order in next session, like if user add some product in cart and he quits before giving order and he is a registered user, then you can save his cart every time in database, so that if he gone away without putting order you can show him his orders next time when he logged in.

You can store users cart data in database using $this->cart->contents(); method of cart class. use like this

$cartContentString = serialize($this->cart->contents());

you will get a string of cart content, you can save this string in database and later use it like

$cartArray = unserialize($cartContentString);
Saturday, December 10, 2022

I'll assume that you need the image saved in the user profiles table.

You need to add this field to the user entity :

public byte[] Image { get;set; }

and set

user.Image = new byte[file.ContentLength];
file.InputStream.Read(user.Image,0, file.ContentLength);

Hope this helps.

Full Example here :

        public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase file)

        if (file != null && file.ContentLength > 0)
            // extract only the fieldname
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

        if (ModelState.IsValid)
            string username = User.Identity.Name;
            // Get the userprofile
            UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

            // Update fields
            user.Image = new byte[file.ContentLength];
            file.InputStream.Read(user.Image,0, file.ContentLength);

            user.FirstName = userprofile.FirstName;
            user.LastName = userprofile.LastName;
            user.Email = userprofile.Email;
            user.Motto = userprofile.Motto;

            user.PlaceOfBirth = userprofile.PlaceOfBirth;
            user.HowManyBikes = userprofile.HowManyBikes;
            user.BesideYourBeth = userprofile.BesideYourBeth;
            user.NicestRide = userprofile.NicestRide;
            user.WorstRide = userprofile.WorstRide;
            user.AmountKmPerYear = userprofile.AmountKmPerYear;
            user.AverageSpeed = userprofile.AverageSpeed;
            user.AbleToChatWhileRiding = userprofile.AbleToChatWhileRiding;
            user.PhoneNumber = userprofile.PhoneNumber;

            db.Entry(user).State = EntityState.Modified;


            return RedirectToAction("Edit", "Account");

        return View(userprofile);
Wednesday, August 24, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :