php编程中连接数据库的四种方法,包括com链接方法、odbc连接方法、php内置函数连接方法、以有连接access数据库的方法方法1<?php
$conn = new Com("ADODB.Connection"); //实例化一个Connection对象
$connstr = "provider=sqloledb;datasource=.;uid=用户名;pwd=密码;database=数据库;";
$conn->Open($connstr);
$rs = new Com("ADODB.Recordset"); //实例化一个Recordcount对象
/*使用实例*/
$rs->Open('select * from News where bigclassid = 59 And LeadPostil is null', $conn, 1, 1);
$count = $rs->RecordCount; // www.junphp.com
echo "共有{$count}条纪录
";
for ($i = 0;$i < $count;$i++) {
$arr_result[$i]['Title'] = addslashes($rs->Fields('Title')->Value); //标题
$arr_result[$i]['Color'] = addslashes($rs->Fields('titlecolor')->Value ? $rs->Fields('titlecolor')->Value : ''); //标题颜色
$arr_result[$i]['WenHao'] = addslashes($rs->Fields('OtherText')->Value); //文号
}方法2 odbc连接数据库<?php
$dbhost = '';
$dbuser = ''; //你的mssql用户名
$dbpass = ''; //你的mssql密码
$dbname = ''; //你的mssql库名
$connect = odbc_connect("Driver={SQL Server};Server=$dbhost;Database=$dbname", "$dbuser", "$dbpass");
/*实例测试*/
$sql = "select * from content";
$exec = odbc_exec($connect, $sql);
while ($row = (odbc_fetch_array($exec))) {
$row['id'] //獲取字段值
. . .
}方法3 php内置函数连接
打开装有php5和apache的服务器上的php.ini文件 去掉;extension=php_mysql.dll前面的分号";" 重启apache服务器。
$dbh=mysql_connect("主机名","用户","密码");
mssql_select_db("mydb", $dbh);
?>方法4 连接Access数据方法<?php
$db = $_SERVER['DOCUMENT_ROOT'] . "/PHP_ACCESS/include/#mydb.mdb"; //這裏最好用$_SERVER['DOCUMENT_ROOT']获取路径
$conn = new COM('ADODB.Connection') or die('can not start Active X Data Objects');
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");
$rs = $conn->Execute('SELECT * FROM contents order by id desc');
while (!$rs->EOF) {
echo $rs->Fields['name']->Value;
$rs->MoveNext();
}
/*释放资源*/
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;