Saulius Antanavicius
Saulius Antanavicius

Reputation: 1381

Constructing URL without item ID and getting right item

I have had this problem for a while,

Let say we have a movies website

And we have a movie named Test-movies123! in the database,

now what I would do is make a URL watch/test-movie123-{$id}/ and then query DB with the ID,

Now the issue with this is that the ID shouldn't be there, how can I go around this ? if I get the test-movie123 from url and search it, I wont find it because it has no ! unless I use LIKE but thats not very trusty...

Anyone could suggest anything ? Would be much appreciated

Upvotes: 1

Views: 216

Answers (2)

zebnat
zebnat

Reputation: 521

To do that, you may have in your database something like the primary_key as "test-movies123".

Imagine you have a control panel, you insert movies in a form. Then use the title Test Movies123! to save it in the database like this example:

id: AUTO_INCREMENT NUMBER keyname: sanityTitle("Test Movies123!") <-- this should save "test-movies123" title: "Test Movies123!" stuff: "blablabla"

note sanityTitle() will be your function to prepare friendly url's from titles.

Then your url will look like watch/test-movie123/ using regex control in url's or watch/?id=test-movie123 raw

You will search for the INDEXED or PRIMARY key, "keyname" in the table, it will output 1 row, with all your stuff.

Upvotes: 2

Jeremy Clifton
Jeremy Clifton

Reputation: 533

Well, you could create a rule for taking the movie title and turning it into a slug. So, you'd know that you always lowercased the title, removed anything other than letters, numbers and dashes, and converted whitespace into a single dash.

Then store that in another column in your database, and be sure you are forcing uniqueness. Take the URL and search that column from that.

From that point you just have to deal with what happens if you have a second video uploaded that produces the exact same slug. There are a number of options for this ... append a random number slug, increment a number and append it, etc.

Upvotes: 4

Related Questions