【问题标题】:PHP GET id from articles.php从articles.php PHP GET id
【发布时间】:2017-02-21 13:47:43
【问题描述】:

我有一个 Articles.php 页面和一个 Single.php 页面。 Articles.php 运行一个列出所有文章的 foreach 循环。每篇文章的 href 锚点为:

<a href="single.php?id=<?php echo $article['id'];

点击文章链接后,网址变为:

example.com/single.php?id=*ID*

我无法在单个页面上获取该文章 ID 以显示特定于该 ID 的 MySQL 行。建议如下:

$id = filter_var($_GET['id'] ?? false, FILTER_VALIDATE_INT);
if($id !== false){
    //show the article, i.e. select * from .... where id = id ...
    echo "WORKING";
}else{
    //show the error like 404
    echo "ERROR";
}

这应该是:

$id = $_GET($article['id'])

我无法完成这项工作。

【问题讨论】:

  • 您好,您如何在尝试获取之前检查 id 是否已设置。 if( isset($_GET['id']) ){ $id = $_GET['id']; } 类似的东西
  • 只需执行echo $_GET['id']; 以确保您获得所需的 id。您还错误地使用了filter_var(),因为那里不允许使用??false
  • 我想多了,现在可以了。非常感谢大家!

标签: php mysql regex


【解决方案1】:

使用..将值发送到另一个页面

<a href="single.php?id=<?php echo $article['id'];?>">Link</a> //missing php close tag here

然后得到它使用

$id = $_GET['id'];

【讨论】:

  • 这很容易成为建议或评论。不全面的答案...
  • @Mueyiwa Moses Ikomi 这是问题的最终答案。php 中的新手犯了错误。
【解决方案2】:
ok lets try this.
on page 1 => article.php
# we assume
database query here

$query = mysqli_query(//query here);
// we then use a while loop

while($q = $query->fetch_array())
{

  echo '<a href="single.php?id='.$q['id'].'">'.$q['article_name'].'</a>'; 

}


ok on page single.php

# we now have example.com/single.php?id=1 eg.

// there are many ways to grab the id

# option 1

 // inside single.php

 // method 1

  $article_id = isset($_GET['id']) ? (int) $_GET['id'] : "";

// method 2

  $article_id2 = "";

  if(isset($_GET['id']))
  {
    $article_id2 = $_GET['id'];
  }


 // now you have the value from the GET method within your local variable scope 
 // so choose any of the method above
 // both works

  hope this helps?

【讨论】:

    【解决方案3】:

    正如Hek mat 所说,您错过了 Clossing 标签:

    <a href="single.php?id=<?php echo $article['id'];?>">Link</a> 
    

    但是您的代码也不正确 $_GET['id'] 总是给出 string "1" 而不是 int 1 并且如果未设置 id 这将导致错误。 所以试试这个:

    if(isset($_GET['id']) && intval($_GET['id']) > 0){
        $id = intval($_GET['id']); // now work with $id its an int now 
        //show the article, i.e. select * from .... where id = id ...
        echo "WORKING";
    }else{
        //show the error like 404
        echo "ERROR";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多