Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying all table names in php from MySQL database

Tags:

sql

php

mysql

Alright, so I'm fairly new to PHP and SQL/MySQL so any help is appreciated.

I feel like I took the right approach. I searched php.net for "MySQL show all table names", it returned a deprecated method and suggested using a MySQL query on SHOW TABLES [FROM db_name] [LIKE 'pattern'] I'm not sure what "pattern" means but, I searched for "SQL Wildcard" and got the "%" symbol. According to everything I found, this should work and output the table names at the end, but it does not. Any suggestions? Thanks in advance.

<?php
if ($_REQUEST["username"]=="coke"&&$_REQUEST["password"]=="pepsi"){
echo 'You have successfully logged in.';
echo '<br />';
echo 'These are your tables:';
echo '<br />';

   $link = mysql_connect("sql2.njit.edu", "username", "password");

   mysql_select_db("db_name") or die(mysql_error());

   $result = mysql_query('SHOW TABLES [FROM db_name] [LIKE '%']');
   echo $result;
}
else
echo 'You did not provide the proper authentication';
?>

I get no errors. The output is exactly what's echoed, but no table names.

like image 632
EGHDK Avatar asked Mar 27 '12 22:03

EGHDK


Video Answer


2 Answers

The square brackets in your code are used in the mysql documentation to indicate groups of optional parameters. They should not be in the actual query.

The only command you actually need is:

show tables;

If you want tables from a specific database, let's say the database "books", then it would be

show tables from books;

You only need the LIKE part if you want to find tables whose names match a certain pattern. e.g.,

show tables from books like '%book%';

would show you the names of tables that have "book" somewhere in the name.

Furthermore, just running the "show tables" query will not produce any output that you can see. SQL answers the query and then passes it to PHP, but you need to tell PHP to echo it to the page.

Since it sounds like you're very new to SQL, I'd recommend running the mysql client from the command line (or using phpmyadmin, if it's installed on your system). That way you can see the results of various queries without having to go through PHP's functions for sending queries and receiving results.

If you have to use PHP, here's a very simple demonstration. Try this code after connecting to your database:

$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
    echo($table[0] . "<BR>");    // print the table that was returned on that row.
}
like image 166
octern Avatar answered Oct 21 '22 00:10

octern


For people that are using PDO statements

$query = $db->prepare('show tables');
$query->execute();

while($rows = $query->fetch(PDO::FETCH_ASSOC)){
     var_dump($rows);
}
like image 29
Sharpless512 Avatar answered Oct 21 '22 00:10

Sharpless512