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)
?>

另外,auto_increment列插入了空值,在php脚本中执行mysql_insert()_id;可获取刚才插入此列的值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值