如何将 ID 更改为 url slug

How to change ID to the url slug

我目前正在做所谓的友好 url 我有一个疑问,那就是是否可以隐藏 url.

的 /id/

目前我的 url 看起来像这样:localhost/blog.php?=31

我希望它看起来像这样:localhost/blog?url_slug=example-for-this [url_slug]

我的代码是:

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;
    
    }

我在几乎所有的论坛上都尝试过不同的方法,但我无法让它工作。

编辑: 我也试过了,但没用

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>

我猜你找不到现有 post 的原因是因为你试图使用 = 来字符串字段。这是有关它的信息 whosebug.com/a/2336940/7265862

我要添加另一个按 slug 字段搜索的函数:

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;
}