ihue ihue - 5 months ago 9
PHP Question

List all the tables in your MySQL database using PHP

I have a hard time trying to list all the tables in my database.




I tried



<?php

//Configuration
$dbname = 'local';
$user = 'root';
$host = '127.0.0.1';
$pass = '';
$date = date('Y-m-d');
$export_type = 'mysql'; // option : mysql | psql
$file_name = $date.'-portal';
$file_path = $file_name;



// Create connection
$conn = mysqli_connect($host, $user, $pass);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";

$sql = "SHOW TABLES FROM $dbname";
$res = mysqli_query($conn, $sql);

if($res != false){

echo "Connected successfully";
$FILE = fopen("output.csv", "w");

$table = array();
while($row = mysql_fetch_array($res)){
$table[] = $row['0'];
}

foreach($tables as $table) {
$columns = array();
$res = mysqli_query($conn, "SHOW COLUMNS FROM $table");

while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$columns[] = "$row[0]";
}
fwrite($FILE, implode(",", $columns)); fwrite("\n");
$resTable = mysqli_query($conn, "SELECT * FROM $table");

while($row = mysql_fetch_array($resTable, MYSQL_NUM)) {
fwrite($FILE, implode(",", $row)); fwrite("\n");
}
}
}else{
die(mysql_error());
}

?>





Result



if($res != false){
//.. everything in here never get executed
}

`$res` kept returning `false`.





What did I do wrong that could have lead to this ?

Answer

Use db in your connection

 mysqli_connect($host, $user, $pass, $dbname);

And use query like this

 $sql = "SHOW TABLES";
Comments