获取表名并打印每个表的第一行

时间:2023-01-08 10:17:57

How do I print the first row of each table?

如何打印每个表的第一行?

<?php
$dbname = 'mysql_database';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}

mysql_select_db($dbname);

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

while ($row = mysql_fetch_row($result)) {
//echo "<br>Table name is: {$row[0]}\n";

// Make a MySQL Connection
$tableQuery = "SELECT * FROM $dbname.$row[0] LIMIT 1";  
$tableResult = mysql_query($tableQuery) or die(mysql_error());

$firstRow = mysql_fetch_array($tableResult) or die(mysql_error());
//echo $firstRow['name']. " - ". $firstRow['age']."<br>";
    //how do i print field name row and first row of values 
    //if I don't know the field names


}

//mysql_free_result($result);
?>

3 个解决方案

#1


3  

You've not changed your default db, either by doing

你没有改变你的默认数据库

mysql_select_db($db_name);

or doing

或做

$tableQuery = "SELECT * FROM $db_name." . $row[0];

so your inner query is failing.

所以你的内部查询失败了。

#2


0  

Change the query like below, it will fetch 1st row in the table

更改下面的查询,它将获取表中的第一行

$tableQuery = "SELECT * FROM ".$row[0]."LIMIT 1";

#3


0  

I'm not sure what you mean by 'the first row of each table' but to limit the results to 1 row use

我不确定'每个表的第一行'是什么意思,而是将结果限制为1行使用

SELECT * FROM tbl LIMIT 1

Note: This simply gets the first row it finds, this may or may not be the first row inserted, it could easily also be the last row inserted. There is no explicit order implied.

注意:这只是获取它找到的第一行,这可能是也可能不是插入的第一行,它也可以很容易地插入最后一行。没有明确的暗示顺序。

#1


3  

You've not changed your default db, either by doing

你没有改变你的默认数据库

mysql_select_db($db_name);

or doing

或做

$tableQuery = "SELECT * FROM $db_name." . $row[0];

so your inner query is failing.

所以你的内部查询失败了。

#2


0  

Change the query like below, it will fetch 1st row in the table

更改下面的查询,它将获取表中的第一行

$tableQuery = "SELECT * FROM ".$row[0]."LIMIT 1";

#3


0  

I'm not sure what you mean by 'the first row of each table' but to limit the results to 1 row use

我不确定'每个表的第一行'是什么意思,而是将结果限制为1行使用

SELECT * FROM tbl LIMIT 1

Note: This simply gets the first row it finds, this may or may not be the first row inserted, it could easily also be the last row inserted. There is no explicit order implied.

注意:这只是获取它找到的第一行,这可能是也可能不是插入的第一行,它也可以很容易地插入最后一行。没有明确的暗示顺序。