1

我想从 MySQL 数据库中获取数据到 .php 文件中的表中。在我的表格的每一行中,我想显示用户可以下载的标题、文本和附件($name)。问题是当我显示它时,我从我的 .php 文件的每个表行的列表中显示的数据库中获取所有附件。因此,我只想从数据库中每行显示一个附件,其 ID 与数据库表行的标题和文本相同。

这是我的数据库表:

CREATE TABLE IF NOT EXISTS `table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(30) NOT NULL,
`text` varchar(30) NOT NULL,
`name` varchar(30) NOT NULL,
`type` varchar(30) NOT NULL,
`size` int(11) NOT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`)  )

我的代码:

<?php
include('config.php');
$sqlget="SELECT * FROM table ORDER BY timestamp DESC";
$sqldata= mysqli_query($dbcon, $sqlget) or die ('error');
echo"<table>";
while ($row=mysqli_fetch_array($sqldata,
MYSQLI_ASSOC)) {
echo "<tr><td>";
echo"<b><font color='#DF01A5'> Title: ".$row['title']."</font></b>";
echo "<br/>";
echo $row['text'];
echo "<br/>";
echo "<b><font color='#DF01A5'>Attachment: </font>";
?>
<?php
$con = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
$db = mysql_select_db('database', $con);
$query = "SELECT  id, name FROM table";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty <br>";
} 
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>
<a href="download.php?id=<?php echo urlencode($id);?>"
><?php echo urlencode($name);?></a> <br>
<?php 
}
}
mysql_close();
echo"</table";
?>
4

4 回答 4

5

只使用一个while循环

$sqlget="SELECT * FROM table ORDER BY timestamp DESC";
$sqldata= mysqli_query($dbcon, $sqlget) or die ('error');
echo"<table>";
while ($row=mysqli_fetch_array($sqldata,MYSQLI_ASSOC)) {
   echo "<tr><td>";
   echo"<b><font color='#DF01A5'> Title: ".$row['title']."</font></b>";
   echo "<br/>";
   echo $row['text'];
   echo "<br/>";
   echo "<b><font color='#DF01A5'>Attachment: </font>";
   echo "<a href=\"download.php?id=".$row['id']."\">".$row['name']."</a><br />\n";
   ...
}
echo '</table>';
于 2013-04-22T17:12:07.917 回答
3

假设您的两个表仅与 ID 相关:

$sql = $db_conn->query("SELECT t1.title, t1.text, t2.ID AS AID, t2.name FROM table1 AS t1 LEFT JOIN table2 AS t2 ON t1.ID = t2.ID ORDER BY t1.timestamp");

echo '<table><thead><tr><th>Title</th><th>Description</th><th>Attachment</th></tr></thead>';
while($row = $sql->fetch_array())
{
    echo '<tr>';
    echo '<td>' . $row['title'] . '</td>';
    echo '<td>' . $row['text'] . '</td>';
    echo '<td><a href="download.php?id=' . urlencode($row['AID']) . '">' . $row['name'] . '</a></td>';
    echo '</tr>';
}
echo '</table>';

未测试,但从这个开始。

于 2013-04-22T16:47:48.327 回答
2

我们需要该表的示例输出。我仍然不确定这些附件是如何存储的。同时,这个 PHP 函数应该只返回一行:http ://www.php.net/manual/en/mysqli-result.fetch-row.php

编辑:不必要的评论。

于 2013-04-22T16:34:31.180 回答
1

对于您的特定情况,这将有助于:

$sqlget = "SELECT `title`, `text`, `name` FROM `table` WHERE `title` = `text`";

享受...

于 2013-04-22T17:16:55.607 回答