title: mysql sort table names by foreign key dependencies in database
body: <p>I need to find out all tables of one database sorted by foreign key constraint. Actually I am copying one database tables to other database. So I get all tables of one database by </p>
  
  <pre><code> SHOW TABLES FROM mydatabase
  </code></pre>
  
  <p>And then loop through the result of this database and create/insert table/records in other database. This works fine if there is no foreign key constraints. But if there are foreign key constraints, then it generates <code>mysql 150 error</code>. Like if above query has returned tables in following orders</p>
  
  <pre><code>Array
  (
      [0] =&gt; Alerts
      [1] =&gt; CompanyGroup
      [2] =&gt; company
  )
  </code></pre>
  
  <p>Now in this order if <code>CompanyGroup</code> has foreign key constraint to <code>company</code> table then my following foreach loop</p>
  
  <pre><code> foreach($tables as $table) {
       $tableinfo = mysqli_fetch_array(mysqli_query($dbConnection1, "SHOW CREATE TABLE $table"));
      mysqli_query($dbConnection2, " $tableinfo[1] ")
   }
  </code></pre>
  
  <p>will throw the error as in second iteration, while creating <code>CompanyGroup</code> table it will reference to <code>company</code> table that doesn't exits in database. </p>
  
  <p>So I would like to know how can I sort tables with foreign key dependenceis. I actually want to get output like </p>
  
  <pre><code>Array
  (
      [0] =&gt; Alerts
      [1] =&gt; company
      [2] =&gt; CompanyGroup
  )
  </code></pre>
  
  <p>This is a general script so I cannot put manual conditions. This script should run on any database. Database can have 200 to 400 tables with million of records. Please guide.</p>