从表中检索行到 str_replace
我在从表中获取数据并使用它来替换 html 文本中的字符串时遇到问题。我需要从表中检索最后 4 行,然后使用 str_replace 自动创建 href。因此,一列是 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 等。
I'm having trouble taking data from a table and using it to replace strings in html text. I need to retrieve the last 4 rows from the table, then using str_replace, automatically create hrefs. So one column is url, one is title, one is description, etc. Then I'll create 4 separate hrefs from each row. What I have so far will work for only the last result. How do I make it work for all 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);
I'd like to be able to output $title2, $link2, $title3, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是执行以下操作:
然后,您最终会得到一个设置为
$urls_array
变量的 html 链接数组。Easiest way to do so would be to do something like this:
Then you end up with an array of html links set to the
$urls_array
variable.使用带有
mysql_fetch_assoc()
的循环。传统上,是while
循环。下面是一个源自 PHP 文档 的示例:
这应该可以帮助您入门。欢迎来到 StackOverflow。
Use a loop with
mysql_fetch_assoc()
. Traditionally, awhile
loop.Here's an example derived from the PHP docs:
That should get you started. Welcome to StackOverflow.