If like me, you often forget what your database tables are called, or need to check if a MySQL table has been created successfully, but don’t have access to a handy control panel or interface, you may need to write a small PHP script to fetch the results you need. Here are a few that I find myself using time and time again:
Connect to your MySQL database
<?php
$db_user = 'joe_bloggs';
$db_pass = 'test123';
$db_host = 'localhost';
$db_name = 'my_database';
$db = mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db($db_name , $db);
?>
Get a list of all tables in a database
<?php
$query = mysql_query("SHOW TABLES");
while ($result = mysql_fetch_array($query)) {
echo $result[0] . "<br>";
}
?>
Get a list of all data in a table
<?php
$db_table = "my_table";
$query = mysql_query("SELECT * FROM '$db_table'");
while ($row = mysql_fetch_assoc($query)) {
print_r($row) . "<br>";
}
?>
I am a British web designer and developer, working for the United Nations out in Geneva, Switzerland, where I live with my lovely wife Zoe.