Вопрос

I have got one piece of code which gives me a list of all the column names for a specific table. Can i use this list as my $row['VARIABLE'] instead of specifying every row?

The current output of the table names can be seen here this is the second paragraph of text, the first ones are my table names (USERS, ADMIN_LOGIN)

I am working on making a small script which will list all the table contents of a table but it is likely the table will change often so i want a script which can auto generate the table of contents without me having to manually re-enter it all as i have done in the second piece of code below?

Thanks guys

<?php
 // Display all sqlite column names for chosen table
    $db = new SQLite3('data.db');
    $tablesquery = $db->query("PRAGMA table_info(USERS)");

    while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
        echo $table['name'] . '<br />';

}

 // Display * from USERS
$db = new SQLite3('data.db');

$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {

      echo "ID = ". $row['ID'] . "\n";
      echo "USERNAME = ". $row['USERNAME'] ."\n";
      echo "AGE = ". $row['AGE'] ."\n";
      echo "LOCATION =  ".$row['LOCATION'] ."\n\n";
      echo "ANYTHING_ELSE = ". $row['ANYTHING_ELSE'] . "\n";
      echo "EMAIL = ". $row['EMAIL'] ."\n";
      echo "PROFILE_APPROVED = ". $row['PROFILE_APPROVED'] ."\n";
      echo "NUMBER_OF_BATTLES =  ".$row['NUMBER_OF_BATTLES'] ."\n\n";
      echo "TOTAL_WINS =  ".$row['TOTAL_WINS'] ."\n\n";

}
?>
Это было полезно?

Решение

Yes, you can use variables for the index values of an array. For example,

$row = array('col_name' => 'column value');
$index = 'col_name';
echo $row[$index]; // Equivalent to $row['col_name']. Prints "column value"

You should be able to accomplish what you want pretty easily using the above logic. Basically just store the column names from the first query into an array, then loop through that array to get the column names each time you print a row.

Give this a try:

 // Display all sqlite column names for chosen table
    $db = new SQLite3('data.db');
    $tablesquery = $db->query("PRAGMA table_info(USERS)");

    $columns = array();

    while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
        $columns[] = $table['name'];

    }

    // Display * from USERS
    $db = new SQLite3('data.db');

    $results = $db->query('SELECT * FROM USERS');
    while ($row = $results->fetchArray()) {

        foreach ($columns as $col) 
            echo $col . " = " . $row[$col] . "\n";


    }

Другие советы

I use the following in order to get a list of columns names in the order they are defined in the table. I use it to populate an insert/select when preserving data.

sel columnname
from dbc.columns
where databasename='databasename'
and tablename='tablename'
order by columnid;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top