php操作数据库分为几个步骤(这里以MYSQL为例):
1,建立连接
$connection=mysql_connect($db_host,$db_username,$db_password);
2,选择数据库
$db_select=mysql_select_db($db_database);
3,执行CRUD操作
$result=mysql_query($sqlstring);
4,关闭连接
mysql_close($connection);

我这里新建个testdb.php保存数据涟接信息,如

<?php
$db_host=’localhost’;
$db_database=’test’;
$db_username=’root’;
$db_password=”;
?>

再新建个DBHelper类,实现通用性

<?php
class DBHelper{
//建立连接
function GetConnection($db_host,$db_username,$db_password){
$connection=mysql_connect($db_host,$db_username,$db_password);
if($connection==false)
die(“Could not connect to the database:<br>”.mysql_error());//输出具体错误信息
return $connection;
}
//选择对应数据库
function DBSelect($db_database){
$db_select=mysql_select_db($db_database);
if($db_select==false)
die(“Could not select the database:<br>”.mysql_error());
return $db_select;
}
//执行CRUD操作
function Excute($sqlstring){
$result=mysql_query($sqlstring);
return $result;
}
//释放资羱
function CloseConnection($connection){
if($connection!=null)
mysql_close($connection);
}
}
?>

测试页面:

<?php
include(‘testdb.php’);
include(‘dbhelper.php’);
$dbhelper=new DBHelper();
$connection=$dbhelper->GetConnection($db_host,$db_username,$db_password);//调用建立方法
$dbhelper->DBSelect(‘test’);//选择数据库
//执行插入操作
$sqlinsstr=”insert into table1 values(2,’test2′,’2009-10-10′)”;
$dbhelper->Excute($sqlinsstr);
//执行修改数据
$sqlu=”update table1 set contents=3 where id=2″;
$dbhelper->Excute($sqlu);
//执行查询
$sqlstring=”select * from table1″;
$result=$dbhelper->Excute($sqlstring);
while($row=mysql_fetch_array($result)){ //mysql_fetch_row只返回数字薮组
echo $row[‘id’].”t”;
echo $row[‘contents’].”t”;
echo $row[‘birthday’].”<br>”;
echo $row[0].”t”;
echo $row[1].”t”;
echo $row[2];
}
$dbhelper->CloseConnection($connection)
?>