检索从表到str_replace的行

时间:2012-01-16 18:26:33

标签: php limit str-replace

我无法从表中获取数据并使用它来替换html文本中的字符串。我需要从表中检索最后4行,然后使用str_replace自动创建hrefs。所以一列是url,一列是标题,一列是描述等。然后我将从每行创建4个单独的href。到目前为止我所做的只是最后的结果。我如何使它适用于所有4?

$query = "SELECT * FROM LINKS ORDER BY id DESC LIMIT 4";
if(!$result = mysql_query($query)){
    // query failed, handle the error here...
    $errors[] = "A fatal error occurred and this page is non-functional at this time!";
    trigger_error("Query failed: $query<br /> Due to: " . mysql_error()); // application error
} else {
    // query worked
    if(!mysql_num_rows($result)){
        // no matching rows
        $main_content .= "No rows were found!\n";
    } else {
        // query matched at least one row, use the results from the query here...
        $row = mysql_fetch_assoc($result);
        $title1 .= $row['title'];
        $link1 .= $row['url'];
    }
}
//string replace arrays
$placeholders = array('LINK1','LINK2', 'LINK3','LINK4');
$replacevals = array($link1, $link2, $link3, $link4);

//replace the areas of the template with the posted values
$page = str_replace($placeholders,$replacevals,$template);

我希望能够输出$ title2,$ link2,$ title3等。

2 个答案:

答案 0 :(得分:1)

最简单的方法是做这样的事情:

...
// query worked
if(!mysql_num_rows($result)){
  // no matching rows
  $main_content .= "No rows were found!\n";
} 
else {
  $urls_array = Array();
  // query matched at least one row, use the results from the query here...
  while ($row = mysql_fetch_assoc($result))
  {
    $urls_array[] = "<a href='" . $row['url'] . "'>" . $row['title'] . "</a>";
  }
}

然后你最终得到一组设置为$urls_array变量的html链接。

答案 1 :(得分:0)

使用mysql_fetch_assoc()的循环。传统上,while循环。

以下是源自PHP docs

的示例
while ($row = mysql_fetch_assoc($result)) {
    echo $row['title'];
}

这应该让你开始。欢迎来到StackOverflow。