根据数据库中的表检查URL

时间:2016-06-28 08:13:45

标签: php mysql url-rewriting

我目前正在通过IIS使用url重写工作,我正在使用以下变量捕获网址

$compiled_url= $_GET["params"];

但是我需要在MySQL的页面表中查看该URL中的最新内容。该表如下所示

tbl_pages
page_id | page_slug | page_parent
--------+-----------+------------
   1    |   posts   | 0
   2    |   daily   | 2

http://www.domain.com/posts/daily

有哪些方法可以检查上面的域并传递参数对数据库并确保它们按照这个顺序存在,所以如果每天向后输入网址,那么它们就会失败到404,因为他们不会在数据库中反映出这种方式

我已经开始使用这种方法,但作为一个例子我的最终结果我想成为一个类或更整洁的选项

$compiled_url = explode("/",$compiled_url); 
$compiled_parent=0;
foreach($compiled_url as $url_decompiled)
{                   
    $url_results = mysqli_query($webapp_db,"SELECT * FROM tbl_pages WHERE page_slug='" . $url_decompiled . "' AND page_parent ='" . $compiled_parent . "'");
    if(mysqli_num_rows($url_results) > 0)
    {
    echo "page found <br>";
    $result = mysqli_fetch_array($url_results);                 
    $compiled_parent=$result['page_id'];
    }
    else
    {
    echo "page not found <br>"; 
    break;
    }

}
谁曾经做过这样的事情?没有使用框架可以使用哪些方法?

2 个答案:

答案 0 :(得分:0)

你可以使用这样的东西(没有测试过),但是你得到了它的要点......

<?php
$compiled_url = explode("/",$compiled_url);

// using alphabet characters for table aliases
$alphabet = explode("","abcdefghiklmnopqrstuvwxyz");

$sql_query = "SELECT * FROM tbl_pages ".$alphabet[0];

// loop to build all the JOINs 
for($i=0; $i<count($compiled_url); $i++)
{
    $sql_query .= " INNER JOIN tbl_pages ".$alphabet[$i+1]." ON  ".$alphabet[$i+1].".page_id = ".$alphabet[$i].".page_parent";
}


// loop to build all the WHERE filters
$where = array();
for($i=0; $i<count($compiled_url); $i++)
{
    $where[] = $alphabet[$i].".page_slug = '".$compiled_url[$i]."'";
}

$sql_query .= " WHERE ".implode(" AND ",$where);

// if results are found print "page found" else print "page not found"
if(mysqli_num_rows($url_results) > 0)
{
   echo "page found <br>";
   $result = mysqli_fetch_array($url_results);                 
   $compiled_parent=$result['page_id'];
}
else
{
   echo "page not found <br>"; 
   break;
}

答案 1 :(得分:0)

您的代码存在问题,您必须在for循环外部检查而不是在其中。我认为你在数据库中添加了一些错误的数据。

因此,请考虑您的表格如下

tbl_pages
page_id | page_slug | page_parent
--------+-----------+------------
   1    |   posts   | 0
   2    |   daily   | 1 // <-- edited from 2 to 1

然后你使用这个脚本

$compiled_url = explode("/",$compiled_url); 
$parent = 0;
$correct = true;
foreach($compiled_url as $item){                   
    $results = mysqli_query($webapp_db,
        "SELECT * FROM tbl_pages WHERE page_slug='" . $item . "' AND page_parent ='" . $parent . "' LIMIT 1"
    );
    if($row = mysqli_fetch_array($result)){
        $parent = $row['id'];
    } else {
        $correct = false;
        break;
    }
}

if($correct){
   echo "page found <br>";
} else {
   echo "page not found <br>"; 
}

根据需要编辑此代码,如果按原样使用,请注意sql注入