Get table names and print first row of each
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);
开发者_JAVA百科?>
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.
Change the query like below, it will fetch 1st row in the table
$tableQuery = "SELECT * FROM ".$row[0]."LIMIT 1";
I'm not sure what you mean by 'the first row of each table' but to limit the results to 1 row use
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.
精彩评论