views:

31

answers:

3

Hi there! I am currently trying to create a PHP script whereby there is already a login script created and the user that successfully logs into the home.php is able to view the tables of the database he is logged into.

Is there any ways of retrieving the tables using the mySQL query like "SHOW TABLES"?

Here are some of my codes:

<?php
session_start();
if($_SESSION['id'])
{
    echo "Welcome ",$_SESSION['username']."<br>";
    echo "Click here to Logout :    ".'<br><a href="logout.php">Logout</a>';
}
else
{
    echo "You don't belong here!";
}



$tableSQL = "SHOW TABLES";

$tablesoutput = mysql_query($tableSQL);

print $tablesoutput;

?>

I think my codes are wrong as there are errors showing that access is denied to the database. Does it mean that I have to reconnect to the database even though I have a session established?

Please do help. Thanks.

A: 

You need to connect to the database every time your skript is executed. The session has nothing to do with your database connection.

softcr
A: 

A session only means that values stored in the $_SESSION variable are persisted across separate requests, but that's all. It does not "log a user into the database" nor does it keep a database connection open. You'll have to establish a database connection on every page load.

You also need to use mysql_fetch_assoc on the result of mysql_query. A simple print won't suffice.

deceze
Instead of using fetch, can I also use mysql_result??
JavaNoob
@Java Sure, if you so wish. You just need *something* more specialized to deal with MySQL results, something `print` can't do.
deceze
+1  A: 

amend the following to suit your requirements:

<?php

$conn = mysql_connect("localhost","foo_dbo","pass") or die("Database error");

mysql_select_db("foo_db", $conn);

$result = mysql_query("show tables");

if(!$result) die("Invalid query: " . mysql_error());

while ($row = mysql_fetch_array($result)){
    echo $row[0], "<br/>";
    //do stuff with the table names
}

mysql_free_result($result);
mysql_close($conn);

?>
f00
Increased answer usefulness! Thanks!
JavaNoob