PHP:无法从动态创建的URL中提取ID

时间:2016-02-05 06:53:32

标签: php url dynamic

我网站上的目标网页使用for循环显示与该部分相关的所有链接(食谱)。这很好用。但是我需要提取在for循环中生成的id,以填充正在生成的页面。

我无法计算如何提取该id值($_REQUEST['id']$_REQUEST['id=?'];我怀疑两者都是错误的)。是通过操纵URL字符串还是有另一种方式?以下是相关代码:

<?php 
                $id = intval($_REQUEST['id']);

                if ($id) {// user gets here by clicking on link with id
                $query  = "SELECT * FROM recipes WHERE uniqno = $id";
                $result = $conn->query($query);
                $row = mysqli_fetch_all($result, MYSQLI_ASSOC);
                $data = $row // fetch data from database

                ?>
                <p><?php echo $data['ingredcontent']; ?></p>

                <?php }
                else {
                foreach ($reciperow as $recipe) { ?>

                <a href="?id=<?php echo $recipe['uniqno'];?>"><h2><?php echo $recipe['rectitle'];?></h2></a>

                <p class="subhead"><?php echo $recipe['recsummary']; ?></p>

<?php }} ?>

如果有人可以建议我应该将哪些内容传递给$ _REQUEST以确保它能够提取出来的内容,我们将不胜感激。在foreach循环中定义。 (注意:我故意远离PHP路由,因为这是一个非常基本的项目。)

1 个答案:

答案 0 :(得分:1)

我尝试修改您的代码如下,请检查这是否是您想要的

<?php 
$conn=new mysqli($hostname, $dbuser, $dbpassword, $dbname);//i assume you have this somewhere

                if (isset($_REQUEST['id'])) {// user gets here by clicking on link with id
                $query  = "SELECT * FROM recipes WHERE uniqno = ".$_REQUEST['id']; //not necessary to convert $_REQUEST to integer
                $result = $conn->query($query);
                $row = mysqli_fetch_all($result, MYSQLI_ASSOC);
                $data = $row // fetch data from database

                ?>
                <p><?php echo $data[0]['ingredcontent']; //you fetch all... need to set index(row) ?></p>

                <?php }
                else {
				//so i assume your $reciperow is fetching all data:
				$query  = "SELECT * FROM recipes"; //not necessary to convert $_REQUEST to integer
                $result = $conn->query($query);
                $reciperow= mysqli_fetch_all($result, MYSQLI_ASSOC);	
				
                foreach ($reciperow as $recipe) { ?>

                <a href="?id=<?php echo $recipe['uniqno'];?>"><h2><?php echo $recipe['rectitle'];?></h2></a>

                <p class="subhead"><?php echo $recipe['recsummary']; ?></p>

<?php }} ?>