Skip to content
Advertisement

How can I get post id from url?

blog.php

URL:

<a href="read.php/<?=seo($post_title).'/'.$post_id?>" class="abtn">Read</a>


I want to get post_id from url. But I don’t know how? I will be glad if you can help me.

read.php

<?php
   
    $sql_query = "SELECT * FROM posts WHERE post_id = ?";
    $select_all_posts = mysqli_query($conn, $sql_query);
                            
    while ($row = mysqli_fetch_assoc($select_all_posts)) {
        $post_date = $row["post_date"];
        $date = strtotime($post_date);
        $newdate = date("d/m/Y", $date);
        $post_title = $row["post_title"];
        $post_text = $row["post_text"];
        $post_image = $row["post_image"];
   }                     
?>

Advertisement

Answer

I can advice next solution:

<?php
    // get page URI and split it by '/'
    $uri_arr = explode('/', $_SERVER['REQUEST_URI']);

    // get post_id and prevent sql injection
    $post_id = mysqli_real_escape_string($conn, $uri_arr[2]);

    // run query
    $sql_query = "SELECT * FROM posts WHERE post_id = $post_id";
    $select_all_posts = mysqli_query($conn, $sql_query);
    
    while ($row = mysqli_fetch_assoc($select_all_posts)) {
        $post_date = $row["post_date"];
        $date = strtotime($post_date);
        $newdate = date("d/m/Y", $date);
        $post_title = $row["post_title"];
        $post_text = $row["post_text"];
        $post_image = $row["post_image"];
    }
                
?>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement