|
|
| Title : |
Accepts a database & hostname from a user and then HTTP username and password. Uses this to connect to a MySQL database. Produces a form based on the tables it finds there to allow the user to do SELECTs, INSERTs, and DELETEs. |
| Categories : |
Databases, PHP, MySQL, Complete Programs |
 Jack McKinney |
| Date : |
Jan 17th 1999 |
| Grade : |
2 of 5 (graded 26 times) |
| Viewed : |
67411 |
| File : |
No file for this code example. |
| Images : |
No Images for this code example. |
|
| Search : |
More code by Jack McKinney |
|
| Action : |
Grade This Code Example
|
|
| Tools : |
My Examples List |
|
|
|
|
|
|
<?php_track_vars?>
<?
# $Header: /usr/local/www/docs/lorentz.com/RCS/mysql.php3,v 1.24 1998/07/28 15:04:13 franklin Exp $
#
# Author: Jack McKinney [email protected]
#
# You may redistribute this as long as you leave this attribution in.
#
# This script accepts a hostname and database name from the user and then
# uses HTTP basic authentication to get a username and password from the
# user. It tries to connect to the named mysql database on the named host
# using the supplied username and password. If it fails, it prompts the
# user for a new username and password.
#
# Once successful, the script queries the database for all tables, and then
# queries each table for all fields. It outputs a form that has a section
# each each table listing each field.
#
# The user can then fill in some or all of the fields, and press one of three
# supplied buttons, SELECT, INSERT, DELETE, to take an appropriate action.
# In using SELECT, there are several special options:
#
# If the value supplied is prefixed by an <, =, >, or ~, then that specific
# comparison is used instead of the default = (~ becomes LIKE).
#
# If the value begins with a '$', the remainder is taken as a field name
# in this or another table (i.e., it is not quoted), so that an inner join or
# self-join can be performed.
#
# FUTURE
#
# - Limit number of results returned per page.
# - Have option to show query as well as results.
# - Have option to not perform query (i.e., use above option to preview first)
# - Have option to enter own query in a TEXTAREA (preferably combined with
# previous option: display query in a TEXTAREA for editing).
# - Ability to click on a record and have the original form displayed with
# this data filled in (for updates and future inserts).
# - Add UPDATE. Hmmm... tricky, tricky, tricky.
# - Add a create table interface (probably in a second script).
# - Add a place to type in special expressions to select (e.g.,
# ROOM.LENGTH*ROOM.WIDTH AS AREA)
#
function bad_auth()
{
global $database;
Header( "WWW-authenticate: basic realm=\"Database ".$database. "\"");
Header( "HTTP/1.0 401 Unauthorized");
$title = "Invalid login";
echo "<HTML>\n";
echo " <HEAD>\n";
echo " <TITLE>Authorization Required</TITLE>\n";
echo " </HEAD>\n";
echo " <BODY BGCOLOR=#FFFFFF TEXT=#000000>\n";
echo " I need a username and password with which to access the database.<P>\n";
echo " </BODY>\n";
echo "</HTML>\n";
exit;
}
$database=$HTTP_POST_VARS[ "DATABASE"];
$hostname=$HTTP_POST_VARS[ "HOSTNAME"];
if(!$database)
{
?>
<HTML>
<HEAD>
<TITLE>MySQL/PHP Interface</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF TEXT=#000000>
<CENTER>
<FORM ACTION=mysql.php3 METHOD=POST>
<TABLE>
<TR>
<TD>Hostname:</TD>
<TD><INPUT TYPE=TEXT NAME=HOSTNAME VALUE="localhost" SIZE=40>
</TR>
<TR>
<TD>Database:</TD>
<TD><INPUT TYPE=TEXT NAME=DATABASE SIZE=40>
</TR>
<TR>
<TD COLSPAN=2 ALIGN=CENTER><INPUT TYPE=SUBMIT NAME=SHOW VALUE=SHOW></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
<?
exit;
}
if(!isset($PHP_AUTH_USER)) bad_auth();
$username = $PHP_AUTH_USER;
$password = $PHP_AUTH_PW;
$dblink = @mysql_pconnect($hostname,$username,$password);
if(!$dblink) bad_auth();
?>
<HTML>
<HEAD>
<TITLE> <?echo "$database@$hostname"?></TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF TEXT=#000000>
<CENTER>
<H1> <? echo "$database@$hostname" ?></H1>
<?
$tableh = mysql_list_tables($database);
if(!$tableh)
{
?>
Could not read list of tables
</CENTER>
</BODY>
</HTML>
<?
exit;
}
$tableno = mysql_num_rows($tableh);
if(!$tableno)
{
?>
MySQL claims this database is empty!
</CENTER>
</BODY>
</HTML>
<?
exit;
}
for($i=0;$i<$tableno;$i++)
{
$table = mysql_tablename($tableh,$i);
$fieldh = mysql_list_fields($database,$table);
$fieldno = mysql_num_fields($fieldh);
for($j=0;$j<$fieldno;$j++)
{
$name = mysql_field_name($fieldh,$j);
$tables[$table][$name][ "type"] = mysql_field_type($fieldh,$j);
$tables[$table][$name][ "len"] = mysql_field_len($fieldh,$j);
}
mysql_free_result($fieldh);
}
mysql_free_result($tableh);
if($HTTP_POST_VARS[ "SELECT"]) $command = "SELECT";
if($HTTP_POST_VARS[ "INSERT"]) $command = "INSERT";
if($HTTP_POST_VARS[ "DELETE"]) $command = "DELETE";
if($command)
{
if(!mysql_select_db($database,$dblink))
{
$error = mysql_error($dblink);
?>
<H1><FONT COLOR=#0000AA>MySQL at <? echo $hostname ?> returned an error:</FONT></H1>
</CENTER>
<FONT COLOR=#DD0000>
<PRE>
<? echo $error ?>
</PRE>
</BODY>
</HTML>
<?
exit;
}
$parts = $HTTP_POST_VARS[ "PARTS"];
for($part=1;$part <= $parts;$part++)
{
$ftable = $HTTP_POST_VARS[ "TABLE".$part];
$ffield = $HTTP_POST_VARS[ "FIELD".$part];
$fdatum = $HTTP_POST_VARS[ "DATUM".$part];
$faction = $HTTP_POST_VARS[ "ACTION".$part];
if(strlen($fdatum))
{
$qdata[$ftable][$ffield] = $fdatum;
$kludge[$ftable] = $ftable;
if(ereg( "^[$]]([^$]][^.]*).",$fdatum,$re) || ereg( "^[<>=~] *[$]]([^.]+).",$fdatum,$re))
$kludge[$re[1]] = $re[1];
}
$qaction[$ftable][$ffield] = $faction;
}
if($qdata)
{
$tablecount = count($kludge);
if($command == "SELECT")
{
for(reset($kludge);$stable = key($kludge);next($kludge))
{
$sfields = $qaction[$stable];
for(reset($sfields);$sfield = key($sfields);next($sfields))
{
$action = $sfields[$sfield];
if($tablecount > 1) $sfield = "$stable.$sfield";
if($action != "IGNORE" && $select) $select .= ",";
if($action == "SELECT") $select .= $sfield;
if($action == "DISTINCT") $select .= "DISTINCT $sfield";
if($action == "ORDERBY")
{
$select .= $sfield;
if($orderby) $orderby .= ",";
$orderby .= $sfield;
}
if($action == "SUM") $select .= "sum($sfield)";
if($action == "COUNT") $select .= "count($sfield)";
if($action == "AVG") $select .= "avg($sfield)";
if($action == "MIN") $select .= "min($sfield)";
if($action == "MAX") $select .= "max($sfield)";
}
}
}
if($command == "SELECT" || $command == "DELETE")
{
for(reset($qdata);$qtable = key($qdata);next($qdata))
{
if($command == "DELETE")
{
$from = $qtable;
$where = "";
}
$qfields = $qdata[$qtable];
for(reset($qfields);$qfield = key($qfields);next($qfields))
{
$cmp = "=";
$qdatum = $qfields[$qfield];
# ereg_replace("''","''''",$qdatum);
if(ereg( "^([<>=~]) +(.*)",$qdatum,$re))
{
$cmp = $re[1];
if($cmp == "~") $cmp = "LIKE";
$qdatum = $re[2];
}
if($command == "SELECT" && ereg( "^[$]]([^$]].*)",$qdatum,$re))
{
$qdatum = $re[1];
if($tablecount > 1 && !ereg( "\.",$qdatum))
$qdatum = "$qtable.$qdatum";
}
else
if($tables[$qtable][$qfield][ "type"] != "int")
{
$qdatum = "'$qdatum'";
}
if($tablecount > 1) $qfield = "$qtable.$qfield";
if($where) $where .= "\n AND ";
$where .= "$qfield $cmp $qdatum";
}
if($command == "DELETE")
$query .= "DELETE FROM $qtable WHERE $where\n\n";
}
if($command == "SELECT")
{
$from = join($kludge, ",");
$query = "SELECT $select\nFROM $from\nWHERE $where\n";
if($orderby) $query .= "ORDER BY $orderby\n";
}
}
else if($command == "INSERT")
{
for(reset($qdata);$qtable = key($qdata);next($qdata))
{
$qfields = $qdata[$qtable];
for(reset($qfields);$qfield = key($qfields);next($qfields))
{
$qdatum = $qfields[$qfield];
if($tables[$qtable][$qfield][ "type"] != "int")
$qdatum = "'$qdatum'";
if($columns) $columns .= ",";
$columns .= $qfield;
if($values) $values .= ",";
$values .= $qdatum;
}
$query .= "INSERT INTO $qtable ($columns)\nVALUES ($values)\n\n";
}
}
echo "<TABLE><TR><TD><PRE>$query</PRE></TD></TR></TABLE>\n";
$start = microtime();
$result = mysql_query($query,$dblink);
$end = microtime();
$start = explode( " ",$start);
$end = explode( " ",$end);
$interval = round(0.5 + 1000*($end[1]-$start[1] + $end[0]-$start[0]));
if(!$result)
{
$error = mysql_error($dblink);
?>
<H1><FONT COLOR=#0000AA>MySQL at <? echo $hostname ?> returned an error:</FONT></H1>
</CENTER>
<FONT COLOR=#DD0000>
<PRE>
<? echo $error ?>
</PRE>
</BODY>
</HTML>
<?
exit;
}
if($command == "SELECT")
{
$colno = mysql_num_fields($result);
$rowno = mysql_num_rows($result);
if($rowno != 1) $s = "s";
echo "<TABLE BORDER>\n <TR>\n";
echo " <TR><TD COLSPAN=$colno ALIGN=CENTER>$rowno result$s, $interval msec</TD></TR>\n";
for($i=0;$i<$colno;$i++)
{
$name = mysql_field_name($result,$i);
echo " <TD><B>$name</B></TD>\n";
}
echo " </TR>\n";
while($rowno--)
{
echo " <TR>\n";
$row = mysql_fetch_row($result);
for($i=0;$i<$colno;$i++)
{
$value = $row[$i];
if(!$value) $value = "";
echo " <TD>$value</TD>\n";
}
echo " </TR>\n";
}
echo "</TABLE>\n";
}
else
{
if($command == "INSERT") $action = "added";
if($command == "DELETE") $action = "deleted";
$rows = mysql_affected_rows($dblink);
$s = "s";
if($rows == 1) $s = "";
echo "$rows row$s $action, $interval msec";
}
}
?>
</CENTER>
</BODY>
</HTML>
<?
exit;
}
?>
<FORM ACTION=mysql.php3 METHOD=POST>
<INPUT TYPE=HIDDEN NAME=DATABASE VALUE=" <? echo $database ?>">
<INPUT TYPE=HIDDEN NAME=HOSTNAME VALUE=" <? echo $hostname ?>">
<?
$parts = 0;
for(reset($tables);$table = key($tables);next($tables))
{
echo "<HR>\n";
echo "<TABLE>\n";
echo " <TR>\n";
echo " <TD COLSPAN=3 ALIGN=CENTER><B>$table</TD>\n";
echo " </TR>\n";
$fields = $tables[$table];
for(reset($fields); $field = key($fields); next($fields))
{
$type = $fields[$field][ "type"];
$len = $fields[$field][ "len"];
$parts++;
echo " <TR>\n";
echo " <TD>$field</TD>\n";
?>
<TD>
<SELECT NAME=ACTION <? echo $parts ?>>
<OPTION VALUE=SELECT SELECTED>Select
<OPTION VALUE=DISTINCT>Select Distinct
<OPTION VALUE=ORDERBY>Order By
<OPTION VALUE=SUM>sum()
<OPTION VALUE=COUNT>count()
<OPTION VALUE=AVG>avg()
<OPTION VALUE=MIN>min()
<OPTION VALUE=MAX>max()
<OPTION VALUE=IGNORE>Don't Select
</SELECT>
</TD>
<?
if($type == "int" || $type == "real")
{
$size=10;
$maxlength=40;
}
else if($type == "string")
{
$size = $len;
if($size > 40) $size = 40;
$maxlength = $len;
$type .= "[".$len. "]";
}
echo " <TD>\n";
echo " <INPUT TYPE=HIDDEN NAME=FIELD$parts VALUE='$field'>\n";
echo " <INPUT TYPE=HIDDEN NAME=TABLE$parts VALUE='$table'>\n";
echo " <INPUT TYPE=TEXT NAME=DATUM$parts SIZE=$size MAXLENGTH=$maxlength>\n";
echo " </TD>\n";
echo " <TD><I>(".$type. ")</I></TD>\n";
echo " </TR>\n";
}
echo " </TABLE>\n";
}
?>
<HR>
<TABLE>
<TR>
<TD><INPUT TYPE=SUBMIT NAME=SELECT VALUE="Select"></TD>
<TD><INPUT TYPE=SUBMIT NAME=INSERT VALUE="Insert"></TD>
<TD><INPUT TYPE=SUBMIT NAME=DELETE VALUE="Delete"></TD>
</TR>
</TABLE>
</CENTER>
<INPUT TYPE=HIDDEN NAME=PARTS VALUE= <? echo $parts ?>>
</FORM>
</BODY>
</HTML> |
|
| bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager Categories : MySQL, PHP, MySQL, Complete Programs, Databases | | | This program allows you to upload an ODBC ressource - i.e. an MS-Access database to a MySQL server. Categories : Databases, MySQL, Complete Programs, PHP, Databases | | | phpMyAdmin is a free software tool written in PHP intended to handle the administration of MySQL over the World Wide Web. Categories : Databases, MySQL, Complete Programs, PHP | | | complete, simple, working example of a login screen/system using php functions, cookies, and a mysql database for begginers. Categories : Authentication, Complete Programs, PHP, MySQL, Databases | | | This program will take data from a user via a web based form, validate it, show it
to the user for re-validation, and finally insert it into the database. Plenty of
sanity checking on the fields in the form.
Categories : MySQL, HTML and PHP, PHP, Complete Programs, Databases | | | Shopping Cart e-Commerce Solution Categories : Complete Programs, PHP, MySQL, Databases | | | Simple Mini Poll class library (SimPoll) Categories : PHP, PHP Classes, Databases, MySQL, Complete Programs | | | AITSH Download Categories : PHP, Complete Programs, MySQL, Databases | | | DDN FFA Network Script Categories : PHP, MySQL, Complete Programs, HTML and PHP, Databases | | | Web Self Service Resource Scheduler Using Session Variables under php4 includes Calendar building code - requires MySQL Categories : PHP, Complete Programs, Calendar, MySQL, Databases | | | DirtSearch Version 3.5 full function robust PHP and MySQL (and other
databases) Site or Web Wide Search Engine
Categories : PHP, MySQL, Complete Programs, Search, Databases | | | Browse a MySQL database & draw a tree view & load final items into a template page. Categories : MySQL, Complete Programs, Algorithms, PHP, Databases | | | Shopping Basket On-Line Ordering System. Categories : Complete Programs, MySQL, PHP, Ecommerce, Databases | | | BBS system for easy customization. Utilizes mySQL. Categories : Complete Programs, MySQL, PHP, Databases | | | Create and restore backup of MySQL databases Categories : MySQL, Databases, PHP, PHP Classes, Complete Programs | |
| |
| | | | | MArtin Cameron wrote : 93
The following errors occur when I access the file:
Warning: Uninitialized variable or array index or property
(HTTP_POST_VARS) in /home/httpd/htdocs/form.php3 on line 63
Warning: Uninitialized variable or array index or property
(HTTP_POST_VARS) in /home/httpd/htdocs/form.php3 on line 64
Warning: Uninitialized variable in
/home/httpd/htdocs/form.php3 on line 65
Can you indicate what I have done wrong?
Regards
Martin
| | | | Boaz Yahav wrote : 94
These are not erorrs, these are warnings.
In most cases you can simply ignore them depending if
the variables are not set cause they don`t need to be or
cause it`s an initialization run or something.
You can make them go away if you add :
error_reporting(0);
at the begining of the script.
| | | | ron parker wrote : 113
Hello,
Is there an appropriate place to ask questions about the
scripts?
I am able to authenticate and read the tables in my
databases; however, when I attempt to "select" I get the
error response "Could not read list of tables."
I notice the script does not echo my hostname which of
course is localhost. So it echos "mydatabase@."
I`d appreciate any hints on debugging my problem. I am real
new to scripting so assume total ignorance.
| | | | Larry Jewell wrote : 124
Hi
This looks like a great learning tool for me. I am pretty unfamiliar with developing php and mysql dynamic
databases.
I was wondering if you could explain something. I have copied this code to notepad and named it db.php3. I
have also taken the mysql.php3 file and transferred it along with the db.php3 file to my asp/php-examples
folder on my linux/apache server. My problem is I`m not familiar with how to insert the information for log
on. I am able to get it all to load onto the server but when I insert my logon information I get an error and
am not permitted on. Is there portions of the code where I must specify logon information in order that it
will recognize my log-on username and password?
Secondly is there a way to have the logon eliminated. I could then just load a link to the database table I
wish people to view. This is being used for a gaming league and so security is not my main priority. Getting
the whole thing running is my first concern. Just for your information my server is ns.rabbits-r-us, my
database is Stealth and the table I wish to utilize is Clanwarmembers. Any help you could give me would be
greatly appreciated as I am pretty useless with this stuff thus far. I guess we all have to start somewhere
and I must tell you how I appreciate the code you are submitting as it assists me in learning the php
language must faster. There are not very many books on MySQL or PHP.
Take care and all the best
Larry Jewell
| | | | Marco Broeken wrote : 147
Warning: Cannot add more header information - the
header was already sent (header information may be
added only before any output is generated from the
script - check for text or whitespace outside PHP tags,
or calls to functions that output text) in e:\program
files\apache group\apache\htdocs\mysql.php3 on line 48
Warning: Cannot add more header information - the
header was already sent (header information may be
added only before any output is generated from the
script - check for text or whitespace outside PHP tags,
or calls to functions that output text) in e:\program
files\apache group\apache\htdocs\mysql.php3 on line 49
I need a username and password with which to access
the database.
This is the error message i get
| | | | Vincent DAVID wrote : 175
Hi,
| | | | Vince DAVID wrote : 176
Hi,
How to use PHP3 with AS/400 database?
I`m working in AS/400 an I think it a good machine for a server but i don`t now to use database
other than JAVA langage (by beans or ODBC).
exist an interpreter for AS/400?
Thanks for your help.
| | | | Paul nami wrote : 192
Broeken Marco ([email protected]) wrote : 147
Warning: Cannot add more header information.............
This is the error message i get.
I got the same message and then just deleted any white spaces before <?
and it should work.
I am having a different problem. After I enter the host and database and submit, I don`t get any
login prompt for user and password. Any ideas?
paul
| | | | Lawrence Sheed wrote : 193
Most of your problems are due to cr/lf issues
Ensure you are uploading in ASCII, not binary.
One change I would make to the script would be to
change line 73 to
<FORM ACTION="<?php echo $PHP_SELF?>"
METHOD=POST>
rather than use a hardcoded name, if you use php_self,
the script will use whatever you named it as for the
form...
| | | | Yogesh Talekar wrote : 312
Hi the example is quite good but nothing is written about
HOW TO USE THIS FILE.... Can I save this whole code as
mysql.php3 in my HTTP-document-root and use it?
I saved the whole code as mysql.php3 but then got following
error.
CAN ANYBODY HELP??
-----------------------------------------------------------
Warning: Cannot add more header information - the header was
already sent (header information may be added only before
any output is generated from the script - check for text or
whitespace outside PHP tags, or calls to functions that
output text) in /home/httpd/html/test/mysql.php3 on line 49
Warning: Cannot add more header information - the header was
already sent (header information may be added only before
any output is generated from the script - check for text or
whitespace outside PHP tags, or calls to functions that
output text) in /home/httpd/html/test/mysql.php3 on line 50
I need a username and password with which to access the
database.
| | | | John Jarrett wrote : 680
HOW TO GET IT WORKING:
Whether you save and upload it wrong or if you cut and paste it from a Windows browser straight to a Unix program window, you will get extra spaces and line breaks that screw it all up.
WARNING: can`t send header info....
1. Delete all blank lines at top of script.
2. Delete all blanks at end of first line between the ?> and the next <?
WARNING: passwords
1. You can`t run this script without your MySQL username and password - get those before you even try.
2. It still doesn`t work even when you put the right authorization info in - open the script and hard code them in. If the script is located in a public or web directory, this is bad security but it should get you running - just BE SURE to fix it later or someone might be able to read the code of the script and see your username and password.
WARNING: SQL error in Line 2 near somefield = `data`
1. Find the ereg replace for ~
2. Go to the end of the line and delete the line break so it is all one line again
3. If there is a space before the + sign in the ereg statement itself - take it out
Almost all of your problems will be (1) from added spaces and messed up line breaks from the cut-and-paste; and (2) you aren`t yet familiar enough with MySQL to know you need a username and password to get in. If you pass the authorization screens, just keep looking for extra spaces where ever it says the script is crashing at.
Those are my fixes so far. Hope they help you, too.
John
| | | | Chinnawat Pongsri wrote :796
I delete the lines with # (comment). It seem work.
After I enter username & password, can display tables.
But it will ask more username & password again.
I try to delete some lines (function bad_auth) and config connect to sever directly.
$hostname=`localhost`;
$username=`myname`;
$password=`mypassword`;
$dblink=@mysql_connect($hostname,$username,$password);
It can show tables, but when I select some table to display... nothings happends.
StoryID, CommentNum, StoryTopic, StoryName, StoryDetail, PostDate, Name, Email, Status, Type, View
The above line is shown fields
SELECT <--- not field here
FROM tbl_dynamic
WHERE StoryID = 2
AND CommentNum = 1
AND Status = 0
MySQL at returned an error:
You have an error in your SQL syntax near `FROM tbl_dynamic
WHERE StoryID = 2
AND CommentNum = 1
AND Status` at line 2
It`s because there are not fields in SELECT field1 ..fieldN.
if($action == "SELECT") { $select .= $sfield;}
The above line return empty for $select, but $sfield have the value.
How can i fix that?
Thanks,
Chin
| |
|
|