Victor Hugo
Victor Hugo

Reputation: 35

How to change ID to the url slug

I am currently doing what is called friendly url and I have a doubt and that is whether it is possible to hide the /id/ of the url.

currently my urls look like this: localhost/blog.php?=31

and I would like it to look like this: localhost/blog?url_slug=example-for-this [url_slug]

IMAGE_TABLE

My code is:

blog.php

<?php include('app/database/db.php');


if (isset($_GET['id'])){
    $id = $_GET['id'];
    $post = selectOne('post', ['id' => $id]);
}

?>

<html>
<p><?php echo $post['title']?></php>
</html>

db.php

function selectOne($table, $conditions)
{
   
    global $conn;
    $sql = "SELECT * FROM $table ";
        $i = 0;
                foreach ($conditions as $key => $value) {
                    
            if ($i === 0){
                $sql = $sql . " WHERE $key=?";
                
            } else {
               $sql = $sql . " AND $key=?"; 
            }
            $i++;
        }
    
        $sql = $sql . " LIMIT 1";
        $stmt = executeQuery($sql, $conditions);
        $records = $stmt->get_result()->fetch_assoc();
        return $records;
    
    }

I have tried different ways in almost all the forum but I can't get it to work.

EDIT: and I also tried this but it doesn't work

blog.php

<?php include('app/database/db.php');


if (isset($_GET['url_slug'])){
    $url_slug = $_GET['url_slug'];
    $post = selectOne('post', ['url_slug' => $url_slug]);
}

?>

<html>
<p><?php echo $post['title']?></php>
</html>

Upvotes: 0

Views: 1112

Answers (1)

Urmat Zhenaliev
Urmat Zhenaliev

Reputation: 1547

I guess the reason that you can not find existing post is because you trying to use = to string field. Here is information about it stackoverflow.com/a/2336940/7265862

I would add another function that searches by slug field:

if (isset($_GET['url_slug'])){
    $url_slug = $_GET['url_slug'];
    $post = selectPostBySlug($url_slug);
}

function selectPostBySlug($slug)
{
    global $conn;
    $sql = "SELECT * FROM post WHERE url_slug like ? LIMIT 1";
    $stmt = executeQuery($sql, [$slug]);
    $records = $stmt->get_result()->fetch_assoc();
    return $records;
}

Upvotes: 1

Related Questions