循环遍历mysql行

时间:2011-11-19 14:11:51

标签: php mysql

如果我有一个看起来像这样的mysql表:

+-------+
| id    |
+-------+
|  3173 | 
| 31793 | 
| 58528 | 
+-------+

如何在PHP中循环遍历所有ID?

3 个答案:

答案 0 :(得分:3)

我建议你阅读一些教程!


1.)连接到您的数据库

mysql_connect('server', 'username', 'password') or die( mysql_error() );
mysql_select_db('db-name') or die( mysql_error() );

2。)SELECT id FROM table_name

$sql = 'SELECT id FROM table_name';
$result = mysql_query($sql) or die( mysql_error() );

$IDs = array();
while ( $row = mysql_fetch_row($result) )
{
  $IDs[] = $row[0];
}

print_r($IDs); // Output the IDs

答案 1 :(得分:0)

这样做,但可能你应该做一些教程

$result = mysql_query('SELECT id FROM tablename');
while ($row = mysql_fetch_assoc($result)){
    echo $row['id']; // this is the ID
}

答案 2 :(得分:0)

您需要连接到数据库:

$link = mysql_connect($host,$user,$password);

然后使用连接链接

检索查询结果
$result = mysql_query('SELECT id FROM my_table_name WHERE 1', $link);

然后迭代抛出行

while(($row = mysql_fetch_array($result)) != false)
{
    // Do whatever you want with the id
    echo $row['id'];
}