I have a PHP script to save new articles into MySQL with the following parameters:
ID, Date, Category, Title, Content, Slug
Where the Slug is the same title but with – dashes like this:
this-is-a-nice-title
Then I have the articles.php where all articles are displayed and linked to read-article.php where the selected article can be read in a seo-friendly url like this
domain.com/news/this-is-a-nice-title
Just like anyone else does, the page read-article.php sends a query to MySQL like this:
SELECT * FROM articles WHERE slug=?
until that everything is fine, every tutorial on Internet tells you to do that and it works.
But here is the problem: If some articles have the same title by any reason, any error or misstake, that would be a problem. So it is best to query using the ID instead like this:
SELECT * FROM articles WHERE id=?
The thing is that I cannot make it to work, I just get error 404 all the time because when there are no results I set it to go to error-404.php while testing/developing
No tutorial teach you how to create friendly urls without querying MySQL by the slug name. Thus my question is: Is it possible to do it another way, tother than to query the slug in MySQL?
2
Answers
This sounds like it’s likely to be an X-Y Problem.
If articles can have the same title, then your system needs to make sure they aren’t saved with the same slug.
For example, if it finds that it’s trying to save a value which is a duplicate of an existing one, then it could append some random character, or a sequence number, a timestamp – anything like that which makes it unique, on the end of the slug.
It probably doesn’t really matter exactly how you do it, the point is to have a process which ensures there can’t be duplicates. It’s generally easier to stop the problem at the source, rather than trying to find workarounds for it.
Ultimately if there are two identical slugs, the system will never be able to tell them apart when parsing the URL, so you can’t allow that to occur in the first place.
There is no question of querying by the ID, because you don’t have the ID at the time you would need it. All you have is the slug value from the URL. That is what shows which post the user has requested to display, and there URL doesn’t contain any other information about that. Therefore, that’s the thing you need to query by, and so to make that work, your system must ensure that each slug is unique in your database.
YES it is possible do achieve in a very easy way:
When you link your visitors using the slug, you simply add the id to it, for example:
And then in the slug page you just query select by ID instead of slug
Don’t forget to edit your htaccess file like this: