选择某些MySQL字段并使用php显示它们

时间:2012-03-28 19:23:13

标签: php mysql database

所以我想做的是我想在名为'filename'的列中搜索某个名称,并在该行上显示'count'。

这可能有助于解释:

我想在'filename'列中搜索Packages,但我想在其上显示'count'(4)

id filename count

1套餐4

2另外7

5 个答案:

答案 0 :(得分:2)

$filename = 'Packages';
$result = mysql_query("SELECT `count` FROM `downloads` WHERE `filename` = $filename");

另请注意,如果文件名可以来自用户输入,则必须注意injection attacks

$filename = 'Packages'; // From user

$filename = mysql_real_escape_string($filename);
$result = mysql_query("SELECT `count` FROM `downloads` WHERE `filename` = $filename");

这是一个选择所有文件名和计数的示例,并将它们列在表中:

$result = mysql_query("SELECT `filename` `count` FROM `downloads`");
?><table><tr><td>Filename</td><td>Count</td></tr><?php
while($row = mysql_fetch_assoc($result)){
    ?>
    <tr><td><?php echo $row['filename']; ?></td><td><?php echo $row['count']; ?></td></tr>
    <?php
}
?></table><?php

答案 1 :(得分:1)

$query = "SELECT count FROM downloads WHERE filename='Packages'";

编辑:

$result = mysql_query($query, $con) or die(mysql_error());

$arr_down = mysql_fetch_assoc($result);

echo $arr_down["count"];

更新:对于包含“Packages”的一行或多行,您可以在表格中显示结果:

$con = mysql_connect("localhost", "MySQL_username", "MySQL_password") or die ("Unable to connect to MySQL Server " . mysql_error());

$fname = "Packages";

$query = "SELECT filename, count FROM downloads WHERE filename='" . $fname . "'";

$result = mysql_query($query, $con) or die(mysql_error());

$html = "<table>\n<tr><th>Filename</th><th>Count</th></tr>\n";

while ($row = mysql_fetch_assoc($result)) 
    $html .= "<tr><td>" . $row['filename'] . "</td><td>" . $row['count'] . "</td></tr>\n";

$html .= "</table>\n";

echo $html;

答案 2 :(得分:1)

假设您真正想要的是每个文件名的下载计数报告,您需要在SQL语句中使用GROUP BY子句:

<?php

$res = mysql_query('SELECT id, filename, COUNT(*) AS count FROM downloads GROUP BY filename');

if (is_resource($res)) {
    while (false !== ($row = mysql_fetch_assoc($res))) {
        printf('%d - %s - %d', $row['id'], $row['filename'], $row['count']);
    }
}

?>

答案 3 :(得分:0)

$count = mysql_num_rows($result)
echo($count)

查看PHP mysql documentation了解更多信息。特别是,您需要了解fetch()函数,您将使用它们来显示使用查询检索的数据。

答案 4 :(得分:0)

原始查询将是:

select count( filename ) from downloads;

编辑:好的,你想把它们循环到页面上:

foreach( $result as $i )
{
  if( !empty( $i ) )
  {
     echo "<div>$i['column_name']</div>";
  }
}