anadikt
@anadikt
Верстка как хобби

Вывод записей не по id, а по колонке slug?

Всем привет, пытаюсь изучать php и на примерах строю свою cms для блога, столкнулся с такой проблемой, что адреса страниц блога открываются по ID, как можно сделать, чтобы страницы открывались по SLUG:

в mysql данные хранятся в posts:
post_id - 1
seo_slug - post-url

сейчас так: https://site.ru/blog/1 
надо так: https://site.ru/blog/post-url


файл .htaccess:

RewriteEngine on
RewriteBase /

RewriteRule ^blog/(.*)$ post.php?p_id=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{THE_REQUEST} /([^.]+).php [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]


файл post.php:

<?php include ("includes/header.php");?>

<?php
  if(isset($_GET['p_id'])){
    $the_post_id = $_GET['p_id'];
    $update_statement = mysqli_prepare($connection, "UPDATE posts SET post_views_count = post_views_count + 1 WHERE post_id = ?");
    mysqli_stmt_bind_param($update_statement, "i", $the_post_id);
    mysqli_stmt_execute($update_statement);
  if(!$update_statement) {
    die("query failed" );
  }
    
  if(isset($_SESSION['username']) && is_admin($_SESSION['username']) ) {
    $stmt1 = mysqli_prepare($connection, "SELECT post_id, post_title, post_date, post_image, post_content, post_views_count, seo_slug, FROM posts WHERE seo_slug = ?");
    } else {
    $stmt2 = mysqli_prepare($connection, "SELECT post_id, post_title, post_date, post_image, post_content, post_views_count, seo_slug FROM posts WHERE seo_slug = ? AND post_status = ? ");
    $published = 'published';
  }
  
  if(isset($stmt1)){
    mysqli_stmt_bind_param($stmt1, "i", $the_post_id);
    mysqli_stmt_execute($stmt1);
    mysqli_stmt_bind_result($stmt1, $post_id, $post_title, $post_date, $post_image, $post_content, $post_views_count, $seo_slug);
    $stmt = $stmt1;
    }else {
    mysqli_stmt_bind_param($stmt2, "is", $the_post_id, $published);
    mysqli_stmt_execute($stmt2);
    mysqli_stmt_bind_result($stmt2, $post_id, $post_title, $post_date, $post_image, $post_content, $post_views_count, $seo_slug,);
    $stmt = $stmt2;
  }
  while(mysqli_stmt_fetch($stmt)) {
?>

  <h1><?php echo $post_title ?></h1>
  <img class="img-responsive" src="images/<?php echo $post_image;?>" alt="<?php echo $post_title ?>" >
  <div class="text-news" ><?php echo $post_content ?></div>

<?php }?>

<!-- Blog Comments -->
<?php 
  if(isset($_POST['create_comment'])) {
    $the_post_id = $_GET['p_id'];
    $comment_author = $_POST['comment_author'];
    $comment_email = $_POST['comment_email'];
    $comment_content = $_POST['comment_content'];
    if (!empty($comment_author) && !empty($comment_email) && !empty($comment_content)) {
      $query = "INSERT INTO comments (comment_post_id, comment_author, comment_email, comment_content, comment_status,comment_date)";
      $query .= "VALUES ($the_post_id ,'{$comment_author}', '{$comment_email}', '{$comment_content }', 'unapproved',now())";
      $create_comment_query = mysqli_query($connection, $query);
      if (!$create_comment_query) {
        die('QUERY FAILED' . mysqli_error($connection));
      }
    }
  }
?>

<!-- Comments Form -->

<?php 
  $query = "SELECT * FROM comments WHERE comment_post_id = {$the_post_id} ";
  $query .= "AND comment_status = 'approved' ";
  $query .= "ORDER BY comment_id DESC ";
  $select_comment_query = mysqli_query($connection, $query);
  if(!$select_comment_query) {
    die('Query Failed' . mysqli_error($connection));
  }
  while ($row = mysqli_fetch_array($select_comment_query)) {
  $comment_date   = $row['comment_date']; 
  $comment_content= $row['comment_content'];
  $comment_author = $row['comment_author'];
?>
<!-- Comment -->

<?php } } else { header("Location: index.php"); }?>

<?php include ("includes/footer.php");?>
  • Вопрос задан
  • 154 просмотра
Решения вопроса 1
Rsa97
@Rsa97
Для правильного вопроса надо знать половину ответа
Чтобы записи выводились по slug, их и в sql-запросе надо запрашивать по slug.
Ваш К.О.
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
delphinpro
@delphinpro Куратор тега PHP
frontend developer
Перенаправить все запросы на единую точку входа

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]


В точке входа реализовать роутер (все равно надо, вы же CMS учитаесь писать).
Роутер в простейшем виде читает $_SERVER['REQUEST_URI'], анализирует его, и передает управление на нужный файл.

Например, ваш url /blog/post-url
$uri = trim($_SERVER['REQUEST_URI'], '/'); // обрезать концевые слеши
$segments = explode('/', $uri); // Разбить в массив по слешам
// и простейший роутинг
switch ($segments[0]??null) {
  case 'blog': 
    $slug = $segments[1];
    include 'blog.php';
    break;
  default:
    echo 'Homepage';
}


В blog.php (псевдокод)

$post = query('SELECT * FROM posts WHERE slug = :slug', ['slug' => $slug]);
if (!$post) {
  echo '404';
  die;
}
echo $post->title;
echo $post->content;
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы