0

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?

3 Answers 3

1

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);

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Increased answer usefulness! Thanks!
0

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.

2 Comments

Instead of using fetch, can I also use mysql_result??
@Java Sure, if you so wish. You just need something more specialized to deal with MySQL results, something print can't do.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.