What's new

Pano to ma fix

loktoy

Eternal Poster
Joined
Oct 20, 2014
Posts
1,168
Solutions
2
Reaction
103
Points
497
Age
30
Warning: Undefined array key "post_id" in C:\xampp\htdocs\post_and_comment_system\home.php on line 33
<?php
$id = $_GET['id'];
$query = mysqli_query($conn,"SELECT *,UNIX_TIMESTAMP() - date_created AS TimeSpent from post LEFT JOIN user on user.user_id = post.user_id where post_id = '$id' order by post_id DESC limit 1")or die(mysqli_error());
while($post_row=mysqli_fetch_array($query)){
$id = $post_row['post_id'];
$upid = $post_row['user_id'];
$posted_by = $post_row['firstname']." ".$post_row['lastname'];
?>
 
The warning message you received is indicating that the array key "post_id" is undefined on line 33 of your home.php file. This means that the variable $post_row['post_id'] is not set or does not exist in the array $post_row.

To fix this issue, you can check if the key exists in the array before trying to access it. You can use the isset() function to do this. Here's an updated version of your code with the necessary fix:

PHP:
<?php
$id = $_GET['id'];
$query = mysqli_query($conn,"SELECT *,UNIX_TIMESTAMP() - date_created AS TimeSpent from post LEFT JOIN user on user.user_id = post.user_id where post_id = '$id' order by post_id DESC limit 1")or die(mysqli_error());
while($post_row=mysqli_fetch_array($query)){
    // Check if the 'post_id' key exists in the $post_row array
    if(isset($post_row['post_id'])){
        $id = $post_row['post_id']; 
        $upid = $post_row['user_id'];   
        $posted_by = $post_row['firstname']." ".$post_row['lastname'];
    } else {
        // Handle the case when the 'post_id' key is not set
        // You can display an error message or take appropriate action
        echo "Error: 'post_id' key is not set in the array.";
    }
}
?>

By using the isset() function, you can prevent the "Undefined array key" warning and ensure that your code only accesses the 'post_id' key when it actually exists in the array.
 

Similar threads

Back
Top