I saved an original image in my database using the following fields:
file_name VARCHAR(255)
mime_type VARCHAR(255)
file_size INT
file_data LONGBLOB
My PHP code for saving is:
$image = $_FILES['image'];
$info = getImageSize($image['tmp_name']);
$query = "CALL saveImageInDataBase('" .
mysql_real_escape_string(file_get_contents($image['tmp_name'])) . "', '" .
mysql_real_escape_string($image['name']) . "', '" .
mysql_real_escape_string($info['mime']) . "', " . $image['size'] . ")";
$result = mysql_query($query);
I want to create a thumbnails of original images out of above data in the server (I'm using PHP) in order to display on the site (to display a list of links of images).
Can someone tell me the simplest way to do this?
You are doing the whole thing wrong.
DO NOT store images in the database. It makes absolutely no sense in the context of an HTML-drven website.
DO NOT create thumbnails on the fly. Create them right after upload and store in the files along with original image.
For the particular code you may search either google or this site. There are over 100500 codes written already I believe.
Related
I am using QRICKIT (qrickit.com) to generate QR codes. Instead of generating codes every time the page refreshes, I want to download them and use the ones already generated.
So, within the loop that iterates through my database table, I do this:
$qrcodebase = "https://qrickit.com/api/qr.php?d=";
$filename = "./product_images/" . $row["itemID"] . "_QR.png";
if (!(file_exists($filename))) {
$url = $qrcodebase . $myurl . $brandpage . "/?itemID=" . $row["itemID"];
file_put_contents($filename, file_get_contents($url));
}
echo "<td><img src=\"" . $filename . "\" height=60 width=60></td>";
When this executes, it generates the right HTML to display the image, and when I FTP to the product_images folder, the QR codes are there. When I download the QR codes and open them up in an image editor, they open just fine. But, when the web page displays, I get an X in a box that indicates a bad image. Does anyone have any idea why?
So, i have the code (for creating table in database ,using BLOB as a datatype) :
$sql = "CREATE TABLE voter_info1 (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL,
img BLOB NOT NULL,
vid VARCHAR(30) NOT NULL UNIQUE,
password1 VARCHAR(65) NOT NULL,
reg_date TIMESTAMP
)";
And storing values in database like :
$sql = "INSERT INTO voter_info1 (firstname,img,,vid,password1)
VALUES ('$firstname','$img','$vid','$password1')";
Is the code correct ?? (according to me it is because the storing of image takes place in database, review needed though!!)
Now, i want to display the image somewhere in the program , here is the code for that :-
$sql = "SELECT * FROM voter_info1 WHERE vid='".$voter_id."' ";
$result_getname = $conn->query($sql);
while($row = $result_getname->fetch_assoc()) {
echo '<img src="$mime,'.base64_encode( $row["img"] ).'"
width="80px" height="80px">';
}
What i figured out is that the image is being stored in database and if i echo the image it gives its name (ex - my_image.jpg) but the image is not being displayed , rather i have a broken link of the image..
What could be the problem ?
To display the image in the html, with php. What is done mainly is that you have a folder where the images are stored and what you save is the file image in that folder and the path of that file as a string and save it.
For example, let's say we have website root cms and inside cms directory we have a folder called images. So, what we do is, in the form we use enctype multipart/form-data, have an input of type file (choose file...) button and save that in php as so:
//Save image in a variable for displaying the form.
$image = $post_image = $_FILES['post_image']['name'];
//Save image in a variable to store it in server.
$post_image_temp = $_FILES['post_image']['tmp_name'];
//Save image to the /image file.
move_uploaded_file($post_image_temp, "{$post_image}");
And finally we can access it by using the image in from the db as (file path might change):
$img = $POST['image']; // /images/image.jpg
Now, do an echo in the src attribute in the of $img. Now we access the file in the server.
The image does not actually get stored in the database, Only the path to the image does, Read into uploading an image with php. Then once you have the code sorted to actually move the file to the path on the server you will have to get the file path and the image name you stored it with and send that data to the database then when you echo out the img you can use the src stored in the database
I highly recommend looking into
https://github.com/verot/class.upload.php
It will save a massive amount of headaches if your dealing with uploading images
It has very good documentation and is very easy to use, and hasnt let me down yet.
There are multiple things to improve in this situation:
$sql = "CREATE TABLE voter_info1 (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL, <-- email size should be increased to 256 # see:
[https://www.rfc-editor.org/errata_search.php?eid=1690]
img BLOB NOT NULL, <-- images should normally not be stored directly in the database, instead a filename or identifier to find it on the disk should be used and stored as a varchar
vid VARCHAR(30) NOT NULL UNIQUE,
password1 VARCHAR(65) NOT NULL, <-- this looks like it might contain the password of the user in plaintext form, that is not recommended, instead an encrypted hash should be stored # see: [http://php.net/manual/en/function.password-hash.php][2]
reg_date TIMESTAMP
)";
Next the INSERT statement:
$sql = "INSERT INTO voter_info1 (firstname,img,,vid,password1)
VALUES ('$firstname','$img','$vid','$password1')";
It should first specify all the columns that are going to be used with backticks(`) around the columns to avoid naming issues.
Also the amount of columns specified should match the amount of values specified, you have one empty column definition.
The final result would then look like:
$sql = "INSERT INTO `voter_info1` (`firstname`,`img`,`vid`,`password1`)
VALUES ('$firstname','$img','$vid','$password1')";
And finally the fetching of data:
$sql = "SELECT * FROM voter_info1 WHERE vid='".$voter_id."' ";
$result_getname = $conn->query($sql);
while($row = $result_getname->fetch_assoc()) {
echo '<img src="$mime,'.base64_encode( $row["img"] ).'"
width="80px" height="80px">';
}
There are a couple of things here to take into consideration.
If you have the image as binary data in the database and you want to make it inline img src, you should prefix it with: src="data:image/png;base64,[binary data here, base64 encoded like you are doing]"
You are using $mime, but the code does not describe what $mime is or if it is set correctly.
Also the code does not show if you are using base64_decode while storing the binary data into the database, that should also be done.
So, in short, the most likely culprit in your code is not specifying the img src tag correctly.
I have a form where users can upload images to my MySQL database. The table has three columns: id, name and image. Image is a blob column with the default settings. I'm able to store the image data, but when I fetch the data and try to display it on the web page, I just get a broken image (in this case it's a jpeg file).
I suspect something has gone wrong with the encoding somewhere. My upload.php file is encoded in UTF-8 without BOM. This is my upload code:
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$insert = $conn->prepare('INSERT INTO images VALUES(:id,:name,:image)');
$insert->bindValue(':id', '');
$insert->bindParam(':name', $image_name);
$insert->bindParam(':image', $image);
$insert->execute();
And this is where I try to display the image.
$select = $conn->prepare('SELECT image FROM images WHERE id = 2');
$select->execute();
$display = $select->fetch();
echo '<img src="data:image/jpg;base64,' . base64_encode( $display['image'] ) . '" />';
I watched a video tutorial on blobs in MySQL, where the blob column had the binaryattribute. However, when I try to create a column like that, I get an error 1064. I don't even know it that has got anything to do with this though.
Firstly, you shouldn't be using addslashes() with prepared statements (not that that's your issue here).
By default ->bindParam() defaults to type PDO::PARAM_STR, so you'll need to specify that the data you're passing is not a string.
Try:
$insert->bindParam(':image', $image, PDO::PARAM_LOB);
Storing binary data in a database can lead to all sorts of issues too. I'd recommend storing the file to disk and just storing the path to it in the DB - it has all sorts of advantages.
I working on an image gallery with the thumbnails and main image on the same page. I have ordered the thumbnails so that the last uploaded image standing on top but I also want that this image is displayed as main image. My site is http://www.robcnossen.nl/view_album.php?album_id=7
I can't find if it can be done with mysql but maybe I am looking right.
I'm trying to find the solution in PHP but all what I find on internet I can't get it working for me.
I thought that array multisort, filectime and ksort would solve my problem but nothing changed.
A part of my code is;
print_r ($images);
//$dirname = dirname(__FILE__);
//filectime($dirname);
//ksort($images);
array_multisort($images, SORT_DESC);
if(isset($image['album'], $image['id'], $image['ext']));
$foto = 'uploads/' . $image['album'] . '/' . $image['id'] . '.' . $image['ext']. '';
$standaardwaarde=isset($_GET['image_id']) ? $_GET['image_id'] :$foto;
echo'<img src="' ,htmlentities($standaardwaarde), '" title="" />';
How can the last uploaded image be shown as main image?
If the $images is a return variable from a DB query, you can change that query by adding an ORDER BY timestamp (I see on your var_dump that there is a timestamp).
If you store it in a mysql database and your image are stored with an auto increment field or a date field you can use the ORDER BY clause to get the last image as the first (inverse order):
ORDER BY id DESC or ORDER BY timestamp DESC.
your main image will be then:
$retrieved_array[0]['field_to_show']
I'm trying to display multiple images using PHP and MySql database, even if using the while loop I don't get all of the images, I only get one, I mean the first one in the table. What's the problem ?
I'm using a table ID_IMAGE (int, pk, auto increment) and myImage (blob)
$query = mysql_query("SELECT myImage FROM image");
while($data=mysql_fetch_array($query)) {
header('Content-type: image/jpg');
echo $data['myImage'];
}
A possible way to solve this problem is to have a separate script to dynamically output the contents of the image eg. :
image.php
header('Content-type: image/jpg');
// DataBase query and processing here...
echo $data['myImage'];
and call it whenever you need to show images stored in your DB eg. inside your loop:
echo '<img src="image.php?id=' . $data['id'] . '">';
But storing images in the database will take a toll on your server and unless they're really small or you have a good reason to do so, you should only store their physical location on the disk.
You can also use this approach if you wish to hide image location from your users, or control access, but there are better and faster alternatives for that case.
Just to mention the possibility to embed the images directly in html by encoding them, you can use this:
$query = "SELECT myImage FROM image";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="data:image/jpg;base64,' . base64_encode($row['myImage']) . '">';
}
}
Pro:
The browser does not need to load the images over an additional network connection
You can query and display multiple images in one request
Con:
If the image(s) are big and/or there will be many images, the page will be load slow
Encoding an image to base64 will make it about 30% bigger.
For more information about base encode images:
http://davidbcalhoun.com/2011/when-to-base64-encode-images-and-when-not-to/
base64 encoded image size