I'm using this code to attemp开发者_如何学Ct to grab a table name and store it in a variable.
<?php
connectDB();
$sql = "SHOW TABLES";
$result = mysql_query($sql);
$tables = mysql_fetch_array($result);
foreach ($tables as $table) {
$table_name = $table[0];
echo $table_name;
}
closeConn();
?>
For one, its outputting 'aa' and 'bb' if i change the array index which i know arent table names in the db and two, what i want to do is run some code for every table in the db and insert the table name into a variable which i can use in said code? How would i do that?
$tables = mysql_fetch_array($result);
mysql_fetch_array
fetches one row, not the entire set. This means that when you do $table[0]
, you are actually working on the string value of each field in the row.
You should put the mysql_fetch_array
inside the loop instead:
while ($table = mysql_fetch_array($result)) {
$table_name = $table[0];
echo $table_name;
}
SHOW TABLES
returns a table with one table name per row. You should use mysql_fetch_array
as many times as there are rows in the table, because it only retrieves one row of the table...
Think of something like this:
while($row = mysql_fetch_array($result)) {
$table_name = $row[0];
// ...
}
$sql = "SHOW TABLES"; $result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_BOTH))
{
$tables[] = $row[0];
}
// To Display
foreach ($tables as $table) {
$table_name = $table;
echo $table_name;
}
精彩评论