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$servernameto the valuelocalhost, which is the default server name for MySQL. -
$username = "username";- This line sets the variable$usernameto the valueusername, which is the username used to connect to the MySQL server. -
$password = "password";- This line sets the variable$passwordto the valuepassword, which is the password used to connect to the MySQL server. -
$dbname = "myDB";- This line sets the variable$dbnameto 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$sqlto 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 TABLEScommand and stores the result in the variable$result. -
if ($result->num_rows > 0) {- This line checks if the result of theSHOW TABLEScommand contains any rows. -
while($row = $result->fetch_assoc()) {- This line loops through each row in the result of theSHOW TABLEScommand. -
echo "Table: " . $row["Tables_in_myDB"];- This line prints out the name of each table in the result of theSHOW TABLEScommand. -
$conn->close();- This line closes the MySQLi connection.
Helpful links
More of Php Mysql
- How to use a MySQL union in PHP?
- How to use MySQL transactions in PHP?
- How to get a single value from query in PHP MySQL?
- How to run multiple queries in PHP and MySQL?
- How to replace a string in MySQL using PHP?
- How to join tables with PHP and MySQL?
- How to update to null value in MySQL using PHP?
- How to escape a string for MySQL in PHP?
- How to write an update query in MySQL using PHP?
- How to get the version of MySQL using PHP?
See more codes...