从mysql获取n个随机行并将它们写入文件

时间:2013-11-08 09:09:14

标签: php mysql

我需要从mysql表中取n个随机行并将它们写入文件。请帮帮我怎样才能用php做到这一点? mysql表的结构是:

CREATE TABLE IF NOT EXISTS `keys` (
  `keyword` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:0)

假设first n行按字母顺序表示前N个,您的代码应该是这样的:

$fd = fopen("/the/filename/you/want","w");
$db = new mysqli($host,$username,$passwd,$dbname);
$rs = $db->query("SELECT `keyword` FROM `keys` order by `keyword` LIMIT $n"); //Being $n the number of rows that you want
while ($row = $rs->fetch_assoc())
{
  fwrite($fd,$row['keyword']);
}
$rs->free();
fclose($fd);