php-mysqlHow to list tables in PHP MySQL?
To list tables in PHP MySQL, you can use the SHOW TABLES
command. This command will return a list of all the tables in the current database.
Example code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SHOW TABLES";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Table: " . $row["Tables_in_myDB"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Output example
Table: mytable
Table: mytable2
Table: mytable3
Code explanation
-
$servername = "localhost";
- This line sets the variable$servername
to the valuelocalhost
, which is the default server name for MySQL. -
$username = "username";
- This line sets the variable$username
to the valueusername
, which is the username used to connect to the MySQL server. -
$password = "password";
- This line sets the variable$password
to the valuepassword
, which is the password used to connect to the MySQL server. -
$dbname = "myDB";
- This line sets the variable$dbname
to the valuemyDB
, which is the name of the database we are connecting to. -
$conn = new mysqli($servername, $username, $password, $dbname);
- This line creates a new MySQLi connection using the variables set in the previous lines. -
$sql = "SHOW TABLES";
- This line sets the variable$sql
to the valueSHOW TABLES
, which is the command used to list all the tables in the current database. -
$result = $conn->query($sql);
- This line executes theSHOW TABLES
command and stores the result in the variable$result
. -
if ($result->num_rows > 0) {
- This line checks if the result of theSHOW TABLES
command contains any rows. -
while($row = $result->fetch_assoc()) {
- This line loops through each row in the result of theSHOW TABLES
command. -
echo "Table: " . $row["Tables_in_myDB"];
- This line prints out the name of each table in the result of theSHOW TABLES
command. -
$conn->close();
- This line closes the MySQLi connection.
Helpful links
More of Php Mysql
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to count the number of resulting rows in a MySQL database using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to fetch data from MySQL in PHP?
See more codes...