Asked  7 Months ago    Answers:  5   Viewed   33 times

My client have created a script in php+mysql that saves images directly in the database and every images has url like this: www.example.com/image.php?id=421

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.

 Answers

70

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.

Wednesday, March 31, 2021
 
buymypies
answered 7 Months ago
85

There could be a few problems here...

1. explode()

First, your explode() may not work if your $row1["offimage"] string doesn't have asterisks * between the file names. In a reply comment to the OP you've given us an example of the contents of $row1["offimage"], which does NOT separate each PNG file by an asterisk *:

@lolka_bolka i get this outout, uploads/c376437e2a45598b2f4d89eae4f191e8.pnguploads/c376437e2a45598b2f4d89eae4f??191e8.png8069756be5095978123ae51fadbffe3b.pnguploads/c376437e2a45598b2f4d89eae4f??191e8.png8069756be5095978123ae51fadbffe3b.png04aaa414c21dc057bc594b896124068e.png 
–  user3732711 Dec 16 '14 at 12:24 

For your script to work as you've written it, we would expect to see, for example, your $row1["offimage"] string looking like this, with an asterisk * separating each PNG file name (with it's directory path):

 uploads/c376437e2a45598b2f4d89eae4f191e8.png*uploads/c376437e2a45598b2f4d89eae4f??191e8.png*8069756be5095978123ae51fadbffe3b.png

2. DIV class 'item'

As "Dan Soap" & "Rohit the developer" have answered here, for carousel to work, you need to make sure each image is wrapped in its own item class.

Your code above has echo"<div class='item'>"; before the while loop.

echo"<div class='item'>"; should be INSIDE the while loop - more specifically it should be inside your foreach loop - so that each image in the carousel is wrapped with the item class.

And don't forget, the item or image you wish to have shown first (on load) should have active class too, as well as the item class, as such: <div class="item active">.

3. JavaScript

You haven't included any JavaScript for us to look at... without calling the carousel() function, nothing will happen, only one (static) image will show. You may need something like this:

<script>
$('.carousel').carousel({
    interval: 3000
})
</script>

Hopefully one / some / all of these can help get your carousel up and running! :)

Wednesday, March 31, 2021
 
Anax
answered 7 Months ago
80

While encoding characters is a good thing, one must make sure not to over-encode.

Only encode what /needs/ encoded at that time. Don't encode the HTML before putting it into your database. You may want to print things out later, or you may want to run searches against it. Use the proper escape sequences for SQL (or, better yet, use PDO).

Only when you are sending things to the browser should you escape the HTML, and then you need to decide what kind of escaping you need. To convert things like < and & as the character entities so they will display properly, then use the right escape method for that.

Wednesday, March 31, 2021
 
superhero
answered 7 Months ago
64

Try this and compare with yours, I don't know if it works because I didn't tested, but it should.

upload.php

include('config.php');

if ($_FILES["file"]["error"] > 0 )
{
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
  else
{
    $filename  = basename($_FILES['file']['tmp_name']);
    $ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

    $new_file_name = md5($filename).'.'.$ext;

    $final_save_dir = $_SERVER['DOCUMENT_ROOT'].DS.'www'.DS.'images'.DS;
    if(move_uploaded_file($_FILES['file']['tmp_name'], $final_save_dir . $new_file_name)) 
    {
        echo "Uploaded";
    } 
    else 
    {
       echo "File was not uploaded";
    }

    try
    {
        $stmt = $conn->prepare("INSERT INTO imgdb ( image ) VALUES ( ? ) ");
        $stmt->bindParam('1', $new_file_name, PDO::PARAM_STR);
        $conn->errorInfo();
        $stmt->execute();
    }
    catch (PDOException $e) 
    {
      echo 'Database Error'.$e->getMessage();
    }
}

fetch.php

<?php
include('config.php');
ini_set('display_startup_errors',1); 
ini_set('display_errors',1);
error_reporting(-1);

try
{
      $stmt = $conn->prepare("SELECT * FROM imgdb WHERE id = 3");
      $conn->errorInfo();
      $stmt->execute();

       while($row = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            echo "<img src='images/".$row['image']."' height='100' width='100'/>"; 
        }
} 
catch (PDOException $e) 
{
     echo 'Database Error'.$e->getMessage();
}
Wednesday, March 31, 2021
 
mozlima
answered 7 Months ago
19

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 :

[HttpPost]
        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);
            file.SaveAs(path);
        }

        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;

            db.SaveChanges();

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

        return View(userprofile);
    }
Thursday, September 23, 2021
 
Grokodile
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :