PHP - Popular dropdown using tables name of a database

0

The title is already self-explanatory. I've tried everything, but I feel like everything I've done is completely wrong, haha. If anyone can help me, I need to do a dropdown where the values to be selected will be names of the tables in my database. Thank you.

[EDIT] The easiest way I see is to pull all the tables through the mysqli_list_tables function and then I would use a while, or to print this in the dropdown. The point is that even this simple function below is not working. I've tried leaving only the fundamental part (the function of listing tables) for testing purposes and even then, nothing works. (Even in my index file, after calling the dropdownAnos () function nothing else works.)

function dropdownAnos () {
  $host = "localhost";
  $user = "root";
  $pass = "root";
  $banco = "teste";

  mysqli_connect($host, $user, $pass);

  $tabelas = mysqli_list_tables($banco);

  print_r($tabelas);
}

I've changed this code countless times, tried every way possible and this was the simplest version I could get. Even so, it does not work. (Good thing I've saved in github, otherwise I would have lost everything haha.)

[FINAL EDIT] I was able to do it, people. I'll post the answer, should anyone fall into this topic:

function dropdownAnos () {
  $str = "";
  $db = new mysqli('localhost', 'root', 'root', 'teste');

  $teste = $db->query('SHOW TABLES');

  while ($t = $teste->fetch_array()) {
    $str = $str .  "<option>" . $t[0] .  "</option><br>";
  }

  echo $str;
}

Thanks to all who helped.

    
asked by anonymous 19.10.2016 / 14:26

1 answer

2

There is no function corresponding to mysql_list_tables() for MySQLi extension, the way is to do a query in the same hand.

You can list all tables in the current database by querying information_schema or its shortcuts ( SHOW TABLES ).

function listarTabelas(){
   $db = new mysqli('localhost', 'usuario', 'senha', 'database');
   $sql = 'show tables';
   $result = $db->query($sql);
   return $result->fetch_all();
}

function criarOptions($itens){
    $options = '';
    foreach($itens as $item){
       $options .= sprintf('<option>%s</option>', $item); 
    }
    return $options;
}

The call may look like this:

<?php $options = criarOptions(listarTabelas()); ?>
<select>
   <?php echo $options; ?>
</select>

Recommended reading:

How to get all the tables in a MySql database

    
19.10.2016 / 15:03