Click here to Skip to main content
14,486,704 members
Rate this:
Please Sign up or sign in to vote.
See more:
<?php
mysql_connect("localhost", "root","") or die ("could not connect to the server");
mysql_select_db("demodemo") or die ("that database could not be found");

$file = $_FILES['image']['tmp_name'];

$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);

mysql_query("INSERT INTO image (id,image) VALUES ('1','{$image}')");
?>

What I have tried:

i have a tried..


<?php
mysql_connect("localhost", "root","") or die ("could not connect to the server");
mysql_select_db("demodemo") or die ("that database could not be found");

$file = $_FILES['image']['tmp_name'];

$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);

mysql_query("INSERT INTO image (id,image) VALUES ('1','{$image}')");
?>
Posted
Updated 16-Mar-20 23:52pm

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 3

Hi,

Storing your image data in your database is really not a good idea. Your database will become heavy with just a few images.

Usually the logic is to upload the image with PHP, then record only the filename in the database. PHP can generate thumbnails on the fly too, what you cannot do if you store the image in a BLOB field.

This said, here's the code, in case there would be a very unique special reason you still want to save BLOB data:

$fp = fopen($_FILES['image']['tmp_name'], 'r');
$filename = $_FILES['image']['name'];
$content = fread($fp, $_FILES['image']['tmp_name']);
// Insert into blob
$query = "INSERT INTO image (id, image) VALUES ('$filename', '$content')";
   
Comments
Richard Deeming 17-Mar-20 7:18am
   
As with the code in the original question, your code is vulnerable to SQL Injection[^]. NEVER use string concatenation/interpolation to build a SQL query. ALWAYS use a parameterized query.

PHP: SQL Injection - Manual[^]
Gilles Migliori (migli) 17-Mar-20 12:15pm
   
You're absolutely right, the query is not protected. It's usual on forums and others to give simple code samples this way.

I don't agree about always using parameterized queries. Some others 100% safe solutions exist, for instance PHP filters or variable type declaration

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100