我有一个 PHP/MySQL 新闻系统,它在主页上显示最新的新闻文章,并在新闻页面上显示完整列表。
最新的文章有点用,但我的问题是,每当我尝试回显新闻页面上的所有新闻文章时,它要么重复相同的文章,要么只输出一篇文章。
**MySQL Information**
id INT AUTO_INCREMENT,
author VARCHAR(xxx),
title VARCHAR(xxx),
message TEXT,
date TEXT,
time TEXT,
PRIMARY KEY(id)
这是插入页(news_center.php)
<form action='/?module=admin&n=news_center_ac' method='post'>
<table align="center" width="68%">
<tr>
<td>Title</td>
<td><input style="width:100%;" type='text' name='news_title' /></td>
</tr>
<tr>
<td height="57">Message</td>
<td><input style="width:100%; height:100%;" type='text' name='news_message' /></td>
</tr>
<tr>
<td colspan='2'><input type='submit' /></td>
</tr>
</table>
这是 news_center_ac.php
<?php
$conn = mysql_connect(*Connection Information*) or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$author == $_SESSION['name'];
if(!empty($_POST['news_title']) || !empty($_POST['news_message']))
{
if(!empty($_POST['news_title']) && !empty($_POST['news_message']))
{
$date = date( 'jS F Y' );
$time = date( 'H:i' );
$query = "INSERT INTO news (id, author, title, content, date, time) VALUES('', '".$author."', '".$_POST['news_title']."', '".$_POST['news_message']."', '".$date."', '".$time."')" or die(mysql_error());
$insert = mysql_query($query) or die(mysql_error());
echo '<p>Successful News Update “'.$_POST['news_title'].'”';
}
else
{
echo '<p>Please fill in all fields</p>';
}
}
?>
这是新闻页面 (/news/index.php) 上的输出
<?php
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
$output = mysql_fetch_array($news);
?>
*CONTENT*
<?php
foreach ($output as $value) {
echo "<p> “" .$output['content'];
echo "”";
echo "Posted:" .$output['date'];
echo " " .$output['time'];
}
?>
我只想让它依次输出每篇新闻文章,我可以在它工作后整理格式。
最佳答案
您误用了 mysql_fetch_array()
。它需要在循环中调用,因为它一次只返回一行。
$conn = mysql_connect("*CONNECTION INFORMATION*") or die(mysql_error());
$db = mysql_select_db( "db372357229")or die(mysql_error());
$news = mysql_query("SELECT * FROM news ORDER BY date DESC,id DESC");
编辑 添加了 htmlentities()
调用以转换 html 特殊字符
while ($row = mysql_fetch_array($news)) {
echo "<p> “" . htmlentities($row['content']);
echo "”";
echo "Posted:" . htmlentities($row['date']);
echo " " . htmlentities($row['time']);
}
关于php - MySQL/PHP新闻系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6641530/