How to select all columns in the database

Asked

Viewed 959 times

0

How to select all columns in the database with the names 'name' and 'date' I have the code

<?php
    $sql = "??";
    if ($rs = $bd->query($sql)) {
      while ($row = $rs->fetch_assoc()) {
        echo $row['data'];
        echo $row['nome'];
      }
    }
    ?>

I need then to select in all tables the columns with these names. I don’t know if this is possible, or I’ll have to do it one by one?

1 answer

2


You can do the SELECT selecting only the fields date and name:

SELECT nome,data FROM sua_tabela

And also you can select all table columns

SELECT * FROM sua_tabela

If you want to select these same columns from all the tables you have in the database and display all the results at once, try this way:

PDO

$query = $bd->query("SHOW TABLES");
while ($result = $query->fetch(PDO::FETCH_NUM)){

  $tabela = $result[0];

  $sql = "SELECT nome, data FROM ".$tabela;
  if ($rs = $bd->query($sql)) {
      while ($row = $rs->fetch_assoc()) {
        echo $row['data'];
        echo $row['nome'];
      }
    } 
  echo '<hr>';//Separa o resultado de cada coluna selecionada
}

Mysqli

$query = mysqli_query($this->conn, "SHOW TABLES");
while($result = mysqli_fetch_array($query)){

  $tabela = $result[0];

  $sql = mysqli_query("SELECT nome,data FROM ".$tabela);

  while($row = mysqli_fetch_array($sql)){

    echo $row['data'];
    echo $row['nome'];
  }
}
  • I don’t think you understand. I’ll be clearer. I need to select these two columns in all existing tables in the database (which in the case are only 6, but all have these two columns). I don’t think you can do that. But if you know any easier way than selecting table by table you are welcome

  • @Danielheringer Editei, see if this is it

  • Fatal error: Uncaught Error: Call to Undefined method mysqli_result::fetch() in C: xampp htdocs Jeancarlos index.php:116 Stack trace: #0 {main} thrown in C: xampp htdocs Jeancarlos index.php on line 116 The line is this: while ($result = $query->fetch(PDO::FETCH_NUM)){ I think it’s because I’m not using PDO connection and yes Mysqli

  • I did it! Thanks. I just switched the $result index to "Tables_in_photos" where 'Photos' is my database

  • OK. If you use Mysqli I put an option for you to use too ;)

  • Thank you! It was very helpful.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.