PHP访问Mysql(代码)

来源:互联网 发布:3d定制女仆2 mac 编辑:程序博客网 时间:2024/05/20 03:42
<?php//包含文件include('db_info.php');//连接mysql$connection = mysql_connect($db_host, $db_username, $db_password);if(!$connection){die("Could not connect to the database:<br />".mysql_error() );}//选择数据库$db_select = mysql_select_db($db_database);if(!$db_select){die("Could not select the database:<br />".mysql_error() );}$select = ' SELECT ';$column = ' * ';$from = ' FROM ';$tables = ' t_codebook ';$where = '';$query = $select.$column.$from.$tables.$where;//查询$result = mysql_query($query);if(!$result){die("Could not query the database:<br />".mysql_error() );}//获取查询结果并显示while($result_row = mysql_fetch_row($result) ){echo 'id:'.$result_row[0].'<br />';echo 'title:'.$result_row[1].'<br />';echo 'describe:'.$result_row[2].'<br />';}//关闭mysql连接mysql_close($connection);?>


使用PEAR的DB类库

<?php//包含文件include('db_info.php');include('DB.php');//连接mysql$DBconnection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");if(!$DBconnection){die("Could not connect to database: <br />".DB::errorMessage());}$query = 'Create table t_student(id int(11) not null,name varchar(20) not null,age int,primary key (id))';//执行sql语句$result = $DBconnection->query($query);if(DB::isError($result)){die("Could not query the database:<br />".$query." ".DB::errorMessage());}echo "Table created successfully!";$DBconnection->disconnect();?>