How to use PHP Session to View MYsql Database Tables?
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.p开发者_如何学编程hp">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?
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);
?>
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.
You need to connect to the database every time your skript is executed. The session has nothing to do with your database connection.
精彩评论