最近刚入门完mysql,正好学了一阵子php就想着如何把mysql的表信息用php打印页面上。现在就把代码贴出来,以便小伙伴们参考。
先是建立mysql连接:
/*建立连接*/
class database{
/*初始化数据*/
public $iP="xx"
;
public $username="xx"
;
public $psw="xx"
;
public $charType="xx"
;
public $selectDb="xx"
;
/*连接mysql*/
function link_mysql(){
mysql_connect(
$this->iP,
$this->username,
$this->
psw);
mysql_set_charset($this->
charType);
mysql_select_db(
$this->
selectDb);
}
/*构造函数*/
function __construct(
$a,
$b,
$c,
$d,
$e){
$this->iP=
$a;
$this->username=
$b;
$this->psw=
$c;
$this->charType=
$d;
$this->selectDb=
$e;
}
}
然后是mysql执行语句:
class sql {
public $sql="xx"
;
/*检查语句是否正确如果正确就打印出来*/
function sqlword(){
$sql1=
$this->
sql;
$result=
mysql_query(
$sql1);
if(
$result===
false){
echo mysql_error();
}
else{
//echo $_SERVER['QUERY_STRING'];
$num=
mysql_num_fields(
$result);
echo "<table border='1'>"
;
/*这是表头*/
echo "<tr>"
;
for(
$i=0;
$i<
$num;
$i++
){
$fieldName=
mysql_field_name(
$result,
$i);
echo "<td>".
$fieldName."</td>"
;
}
echo "</tr>"
;
/*这是数据库信息*/
while(
$re=
mysql_fetch_array(
$result)){
echo "<tr>"
;
for(
$i=0;
$i<
$num;
$i++
){
$fieldName=
mysql_field_name(
$result,
$i);
echo "<td>".
$re[
$fieldName]."</td>"
;
}
echo "</tr>"
;
}
echo "</table>"
;
}
}
/*构造函数*/
function __construct(
$g){
//parent::__construct();
$this->sql=
$g;
}
}
mysql_num_fields
是取得结果集中字段的数目 用法:mysql_num_fields ($result )
mysql_field_name 是
取得结果中指定字段的字段名 用法:mysql_field_name ( $result , $field_index )
mysql_fetch_array 是从结果集中取得一行作为关联
数组 用法:
mysql_num_fields ($result )
最后是建立对象:
/*连接*/
$final=
new database("localhost","root","123","utf8","task04"
);
$final->
link_mysql();
/*选择数据库*/
new sql("use task04"
);
/*对数据库里面的文件进行操作*/
$final2=
new sql("select * from list"
);
/*打印在页面上*/
echo $final2->sqlword();
实现结果:
转载于:https://www.cnblogs.com/dirkhe/p/6675592.html
相关资源:JAVA上百实例源码以及开源项目源代码