Storing Images in a mysql database - php

what is the best way to uniquely store and image name in a DB, assuming two persons have the same image name, or the same user uploads the same image twice. How can i manage scenerios like this so that when i want perform operations like updating, deleting, i don't end up deleting both images or all. My DB is MySQL.
Edit - Ok, now for some reason i generated a unique time stamp for all the image everything work on localhost, but when i take it online it doesn't work, i cannot delete it, but it works offline well.
Thank you
#cybeormin

In any table I would recomend an ID column that that is Auto Increment and set to the Primary Field. That way all rows are unique despite a user have two images of the same name.

Put a refcount on the images. When you want to delete the image just decrement the refcount instead. When the refcount hits 0, you delete the row for real (or have a cron job delete it).

I would discard the original image name, give every image an unique id and store the original name in the db.

In your mySQL DB, create a table for image uploads, create an ID column set to AUTO_INCREMENT, INT (integer) and make it the PKEY (primary key).
This will mean your ID's are always automatically created and generated when new content is added, and are always unique regardless of whether the same image is added any number of times.
Additional fields can then trap the other image information (filename, 'given' name, filesize, filetype and a BLOB field for the image itself), you can then also even add a psuedo ID which you make up based on any combination of factors..should you see fit.

Associate an unique key (primary key) with each entry. Something like:
fileId | file_name | file
and set the fileId to be auto incrementing and a primary key. You can then on your "user" table (if you have something like that) simply reference the fileId as a foreign key.
userId | ... | fileId | ...
Then, if you need to delete the file, simply use the fileId to find the one you which to delete.

Related

Saving Google image links and its keywords in db or text file

I need to parse Google Images for a specified keyword(s) and retrieve image links, which I can do with PHP simple dom parser, and can retrieve a few image links per call. Google Images API is limited to 100 calls right now. Now, I need to save those image links for a "keyword" so that next time when I need images for that keyword, my script first looks for whether keywords and its related images (i.e. URL's) are already stored in my system and whether there is any need to call Google.
What would the most efficient way to store that keyword and images (i.e. db or simple text files)?
If it is mySQL then what does its schema look like?
Can I store image links in a text file where the file name is keyword?
I would suggest using mysql, choosing it gives u flexibility, speed and easy access to your data. Just put info about your images in one table, something like:
id | name | keyword | path | creTime | size | ext ( and any other that u would need )
Then you can just pull any number of images by Keyword, like "water", "views", or something.
I would probably make two tables of it, changing keyword for keywordId. Then create foreign key to Keyword_data. Now you have relation One ( keywordId ) from Images_data to Many ( id ) keyword_data.
id | keyword | description | ( anything else)
That way you can have multiple keywords for any image group, as it would be more flexible.
I usually like working with relational databases because you can do more with them as you grow. I would also add timestamps to your data (as shown below) so you can know when your links were cached (cause that's effectively what you are doing). Here is the schema I would use:
Images Table
id - Integer, primary index, autoincrement
keyword - Varchar(50), indexed
url - Varchar(2083)
created_at - Timestamp
updated_at - Timestamp
Any other data you want to store, like image type, size, etc.
The length of the URL was based off of this post.
If you wanted to normalize your data even further, you could do this:
Images Table
id - Integer, primary index, autoincrement
keyword_id - integer, indexed
url - Varchar(2083)
created_at - Timestamp
updated_at - Timestamp
Any other data you want to store, like image type, size, etc.
Keywords
id - Integer, primary index, autoincrement
word - Varchar(50)
created_at - Timestamp
updated_at Timestamp
Any other data you want to store
Personally, I would probably just go with the first option because it's simpler (depending on how big your data will get).

can i get primary key value and extension after inserting in database using triggers in MySQL

Well, let me explain this as simple as possible, basically i have a table doc_info, which stores information regarding uploaded files; like file name, date created, uploaded by etc;
what i want is to create an INSERT trigger on this table, which will get two things, the primary key ID of this newly inserted row and the extension of the uploaded filename which will be in the document name; and concatenate them and update that same row, with this concatenated value
Example,
If someone uploads "document.docx", then ID will be auto generated as x and document name will be document.docx, thus the value to store will be "x.docx" using update on that same row.
I am new to this MySQL, and have little knowledge if operations like this can be performed with MySQL.
To implement such action within db you should create two triggers: after insert and on update. They should be like this one
delimiter |
CREATE TRIGGER changeProperty AFTER INSERT ON doc_info
FOR EACH ROW
BEGIN
UPDATE doc_info SET doc_info.someProperty = CONCAT(doc_info.id, doc_info.extension) WHERE doc_info.id = NEW.id;
END;
|
You can calculate extension on you file name by following expression: SUBSTRING_INDEX(doc_id.fileName, '.', -1);

getting id of last query when multiple queries are made

In php have a form with a textarea and a file upload. In mysql I have table 1 with rows for each uploaded file having data like name, size, etc... and I have table 2 with the data entered in the textarea and a column with the id of the file uploaded.
I'm using mysql_insert_id to get the id of the last inserted row in table 1 (the id of file uploaded). Then I insert that id in table 2.
Assuming that multiple uploads are made at the same by different users will mysql_insert_id return the proper id each time? What happens if 2 users upload at the exact time.. Or there is a timeout.. I guess I'm asking if there's a better way to insert a newly created id to 2 tables at the same time?
It returns the id of inserted row for the session from which the insert has been made. So yes, you're doing it just fine.
mysql can't give twice the same value if of course you have the auto-increment on the primary key of the table
Per the php docs (mysqli::$insert_id) last_insert_id function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. Thats for the specific resource you are using; other resources will not affect each other

Auto Increment two fields in SQL?

I was wondering if there is a way to Auto Increment two columns in the same table.
I have database with user_id so every registred user would have his unique nr.
But I want to add a file_id so every file the user upload gets a unique number.
Any tips ?
Thanks
To ensure your database is normalized correctly, you should store file uploads in a separate table.
This means one user has the potential to have multiple files and allows the table to correctly increment the identity field of the file records.
You can read about database normalization on Wikipedia:
http://en.wikipedia.org/wiki/Database_normalization
No, only one identity column per table is allowed.
if you are using SQl Server follow this:
If your second field is static (you dont have to edit and it follows a sinmple logic to generate its value)
what you can do is create the second field as a calculated one, for example:
create table autoINC(
field1 int identity(1,1),
field2 as field1+1,
real_field varchar(50))
insert into autoINC values('test')
select * from autoINC
1 2 test
if you need to update your second field, then you need to use a trigger
I think you could use a trigger or similar solution depending on the database.
In MSSQL a trigger on update should work.
But this will not ensure unique file names unless the filename also includes the userid.
Is there a reason you need fileid to be sequential for each user?
If not, add a userid field to the file table and have a separate fileid identity column in that.

Entry current id

I have an application which keeps database of all nearby restaurants.
When adding a new entry, there is an option to add a few images of your restaurant.
Now the problem:
I'd like to sort the different restaurant images into separated folders, named by restaurant id stored in mysql auto increment ID. The only problem here is, that i dont know that id in advance.
Form example:
text input - title
text input - address
text input - phone
file input - image
file input - image
So, what should I do now?
I. Get the last id, lock the table, create folder named by id, store images inside, store information to mysql database including image paths, unlock table.
or
II. Store all information excluding images paths to mysql database, use PHP mysql_insert_id, create folder named by id, store images inside and store images paths to mysql database.
or
III. Better solution?
This kind of thing is usually done with your option II. Store in the database the main row of information, get the last insert id via mysql_insert_id() or the native MySQL LAST_INSERT_ID() function, then proceed to store rows in any related tables if necessary and create the image directory to store filesystem data.
Assuming the image paths you intend to store in the database will go into a different table with a one-to-many relationship back to the main restaurant table, you'll need to know the last insert id to insert them anyway. Don't worry much about doing it in multiple operations -- that's exactly the reason most RDBMS have a function like LAST_INSERT_ID().
If you are using the autoincrement column. You can right after your insert statement call the last_insert_id() function to retrieve the id of the last inserted record.
See this link for documentation:
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
Its important that you do this within the same transaction/connection otherwise the value might be erroneous.
I don't see a need to use the restaurant's id to organize the pictures - especially since you get into the timing issues you describe. I'd create another unique id - call it picture_folder_id or something - and use that to name the folder for the pictures. As long as you enforce uniqueness on that id, you won't get any collisions, and you won't have any timing problems or locks.

Categories