您的位置:首页技术文章
文章详情页

PHP5对Mysql5的任意数据库表的管理代码示例(一)

【字号: 日期:2024-02-14 14:01:12浏览:47作者:猪猪

PHP5+Mysql5+Apache2已经是目前最流行的建站模式了。在对Mysql的表操作的时候如果仅仅使用sql语言对Mysql去操作未免太繁琐了一点。于是笔者参考互联网上的代码通过修改写了一套对各种表进行添加、删除、修改记录的php代码。仅供大家参考娱乐。

以下贴出的代码在PHP5+Mysql5+Apache2 for WinXp上调试通过。

首先说明一下代码适用范围,按照大多数表的特点,每个表都有id,所以这些代码适用于第一列为id的表。至于名称起什么无关紧要,重要的是代码都是默认按照第一列为primary key来进行操作。其他并无任何限制,本代码可以对任意列的表进行操作。缺点:未进行输入审查。所以输入记录时不要空行也不要输不匹配的类型,这个需要与Mysql的建表相配合。

注意:提醒!以上代码在copy的时候一定注意在编辑器里面把每一行代码前面的tab去掉,不然php5编译不过。而且在每个文件中$database目前为sunsite,$table为software,这个可以根据需要修改。

首先是index.php,主要实现功能为让用户输入表名,然后点击查看按钮就可以看到表的内容。也是默认的首页。

//index.php

<html><meta http-equiv='Content-Type' content='text/html; charset=gb2312' /><title>admin</title><body bgcolor=#ffffff><h2>Please input the table name</h2><form method='post' action='tables.php'><table width=90% align=center><tr>table name: <input type=text name='tablename' size=30 maxlength=30><input type=submit value=show></tr></table></form></body></html>

然后是tables.php,功能为显示出表的内容。并附有添加删除和修改的入口。 //tables.php

<html><title>current table</title><meta http-equiv='Content-Type' content='text/html; charset=gb2312' /><body bgcolor=#ffffff><?$database = 'sunsite'$tablename = $_REQUEST['tablename'];echo '<h2>Data from $tablename</h2>'mysql_connect('localhost','root','') or die ('Problem connecting to DataBase');$query = 'show columns from $tablename'$result = mysql_db_query($database,$query);$column = 0;if ($result){echo 'Found these entries in the database:<br><p></p>'echo '<table width=90% align=center border=1><tr>'while ($r = mysql_fetch_array($result)){echo '<td align=center bgcolor=#00FFFF>$r[0]</td>'$column = $column + 1;}echo '</tr>'mysql_free_result($result);

$query = 'select * from $tablename'$result = mysql_db_query($database, $query);if ($result) while ($r = mysql_fetch_array($result)){echo '<tr>'for($col=0;$col<$column;$col++) echo '<td>$r[$col]</td>'echo '</tr>'}echo '</table>'}else echo 'No data.'mysql_free_result($result);if ($column != 0)//($tablename == 'software' || $tablename == 'techtalk')echo '<p></p><ul><li><a href='https://www.haobala.com/bcjs/index.php'>Home</a><li><a href='https://www.haobala.com/bcjs/add.php?tablename=$tablename'>Add a new entry</a><li><a href='https://www.haobala.com/bcjs/edit.php?tablename=$tablename'>Edit an entry</a><li><a href='https://www.haobala.com/bcjs/del.php?tablename=$tablename'>Delete an entry</a></ul>'?></body></html>

待续。

标签: PHP