欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php连接数据库的四种方法

程序员文章站 2024-01-29 14:38:40
...
  1. $conn = new Com("ADODB.Connection"); //实例化一个Connection对象

  2. $connstr = "provider=sqloledb;datasource=.;uid=用户名;pwd=密码;database=数据库;";
  3. $conn->Open($connstr);
  4. $rs = new Com("ADODB.Recordset"); //实例化一个Recordcount对象
  5. /*使用实例*/
  6. $rs->Open('select * from News where bigclassid = 59 And LeadPostil is null', $conn, 1, 1);
  7. $count = $rs->RecordCount; // bbs.it-home.org
  8. echo "共有{$count}条纪录
    ";
  9. for($i = 0; $i
  10. $arr_result[$i]['Title'] = addslashes($rs->Fields('Title')->Value);//标题

  11. $arr_result[$i]['Color'] = addslashes($rs->Fields('titlecolor')->Value?$rs->Fields('titlecolor')->Value:'');//标题颜色
  12. $arr_result[$i]['WenHao'] = addslashes($rs->Fields('OtherText')->Value);//文号
  13. }
复制代码

方法2,odbc连接数据库

  1. $dbhost = '';

  2. $dbuser = ''; //你的mssql用户名
  3. $dbpass = ''; //你的mssql密码
  4. $dbname = ''; //你的mssql库名
  5. $connect=odbc_connect("Driver={SQL Server};Server=$dbhost;Database=$dbname","$dbuser","$dbpass");

  6. /*实例测试*/
  7. $sql="select * from content";
  8. $exec=odbc_exec($connect,$sql);
  9. while($row = (odbc_fetch_array($exec)))
  10. {
  11. $row['id'] //獲取字段值
  12. ...
  13. }
复制代码

方法3,php内置函数连接: 打开装有php5和apache的服务器上的php.ini文件 去掉;extension=php_mysql.dll前面的分号";" 重启apache服务器。

  1. $dbh=mysql_connect("主机名","用户","密码");
  2. mssql_select_db("mydb", $dbh);
  3. ?>
复制代码

方法4,连接Access数据方法

  1. $db=$_SERVER['DOCUMENT_ROOT']."/PHP_ACCESS/include/#mydb.mdb"; //這裏最好用$_SERVER['DOCUMENT_ROOT']获取路径
  2. $conn = new COM('ADODB.Connection') or die('can not start Active X Data Objects');
  3. $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");
  4. $rs = $conn->Execute('SELECT * FROM contents order by id desc');
  5. while(!$rs->EOF)
  6. {
  7. echo $rs->Fields['name']->Value;
  8. $rs->MoveNext();
  9. }
  10. /*释放资源*/
  11. $rs->Close();
  12. $conn->Close();
  13. $rs = null;
  14. $conn = null;
复制代码