Using PHP with Forms

This page will provide an example login form for authenticating to mysql server. It also establishes a user session, and processes the results of the form. It connects to the database server after the form has been submitted and shows a list of available databases for review.

The section about sessions explains how that part of the code works. The section called "MySQL Example" has the code that allows the user to select a table in the database and display the contents of the table. The listing of the "dblist.php" file is shown in that section which is numbered as item 14.

Here's the code:

<?php
session_start();
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <meta name="description" content="Database Login">
   <title>Database Login</title>
</head>
<body>

<?php

if ($submit)
{
	$chandle = mysql_pconnect("localhost", $username, $password) 
	   or die("Connection Failure to Database");
	$dblist = mysql_list_dbs($chandle);
	echo "<H3>Available Databases:</H3>";
	echo "<UL>";
	while ($row=mysql_fetch_object($dblist))
	{
		echo "<LI><A href=\"dblist.php?", $row->Database, "\">", $row->Database, "</A><BR>";
	}
	echo "</UL>";
	session_register("location1");
	session_register("username");
	session_register("password");
	$location1="database";
	mysql_close($chandle);
}
else
{
// Form has not been submitted
?>

<H1 style="text-align: center">Database Login</H1>
<DIV style="text-align: center">
<form action="login.php" method="POST">
<table>
<tr>
<td>Login Name:</td>
<td><input type="text" name="username" length=10 maxlength="40"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" length=10 maxlength="40"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="Login"></td>
</tr>
</table>
</form>
</DIV>

<?php
$sname=session_name();
}  // End of else not $submit
?>

</body>
</html>

The $submit variable only exists after the form submission has been performed. Therefore, this page is used both to produce the form, and accept input from the form. A link is provided for each file for every available database and the user can then select the link. The name of the database the user selected is provided after the question mark, ?, and is available in the CGI variable, QUERY_STRING. This is shown in the next file called dblist.php:

PHP Manual Contents Page