Ken Adams
Ken Adams

Reputation: 35

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"];
   }                     
?>

Upvotes: 1

Views: 494

Answers (1)

Slava Rozhnev
Slava Rozhnev

Reputation: 10163

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"];
    }
                
?>

Upvotes: 1

Related Questions