Ty Bailey
Ty Bailey

Reputation: 2432

SEO friendly URL's and querying a database php

I've searched for an answer to this question already and found an article relating to it but it does not give an exact answer. That can be found here: PHP - How can I replace dashes with spaces?

I am using this function to convert my blog titles into SEO friendly URL strings:

//SEO Friendly URLS
public static function Seo($input){
    $input = str_replace(array("'", "-"), "", $input); 
    $input = mb_convert_case($input, MB_CASE_LOWER, "UTF-8"); 
    $input = preg_replace("#[^a-zA-Z0-9]+#", "-", $input); 
    $input = preg_replace("#(-){2,}#", "$1", $input); 
    $input = trim($input, "-"); 
    return $input; 
}

which will convert titles like so "My Blog Title" to "my-blog-title", which is good. However I usually pass the blog ID in the URL to get the blog from the database, but I'm trying to keep really friendly urls.

I understand I can pass the blog ID as a second query string on the end of the title like mysite.com/page.php?post=my-blog-post&id=1 but that still looks bad. I WILL be using .htaccess to remove the .php and '?' from the URL's, but I am unsure how to keep a pretty URL while passing the ID too.

How can I query the database while using the blog title as the URL query?

Upvotes: 0

Views: 2152

Answers (2)

Arnis Juraga
Arnis Juraga

Reputation: 1045

You can use mod_rewrite module for Apache. This is the most common practice.

Using .htaccess rewrite rule

RewriteRule ^([^?]*) index.php?route=$1 [L,QSA]

URL http://example.com/en/my-life/first-impression will be "rewritten" and passed to index.php as GET parameter route.

Exploded it in PHP by dashes.

$parts = explode('/', $_GET['route']);

This is how you will get all parts of url and make your PHP logic accordingly,

$parts[0] => language code
$parts[1] => category
$parts[2] => post SEO title

Upvotes: 0

bradym
bradym

Reputation: 4961

URL friendly versions of titles are often referred to as slugs. If you store the slug in the database table you could use it to retrieve articles. It would be best to store the slug anyway so that once a slug is created it is never changed.

For example, let's say you find and fix a bug in the Seo function, there's a possibility that it could change your URL, which is obviously bad SEO. Storing the slug in the database avoids that issue.

If you store the slug, you'll probably want a slug for each blog category as well. This way you're more closely imitating a filesystem and would no longer have to ensure that every slug was completely unique. While it's unlikely you'd have articles with the same title in different directories, it's something to consider as you build your site.

Upvotes: 4

Related Questions