本文为大家介绍php连接不同数据库的几种方法,供大家学习参考。
1.Com链接,ADODB.Connection
代码如下:
$conn = new Com("ADODB.Connection"); //实例化一个Connection对象
$connstr = "provider=sqloledb;datasource=.;uid=sa;pwd=123456;database=jnold;";
$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;
echo "共有{$count}条纪录<br />";
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连接mssql
代码如下:
$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_mssql.dll前面的分号";"
重启apache服务器即可
其次:将安装有sqlserver2000的服务器数据库打上sp3补丁,因为打上sp3补丁,可以开启1433端口.
最后,web服务器上安装sqlserver2000客户端工具
代码如下:
<?
$dbh=mssql_connect("192.168.12.124","sa","");
mssql_select_db("mydb", $dbh);
?>
这个方法经常会连接不上,好像是一个dll文件版本的问题
4.连接access数据的方法
代码如下:
$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;
5.连接MySQL方法:
代码如下:
$database_connection=null;
$hostname="localhost";
$database="5aart";
$username="root";
$password="1234";
global $database_connection;
$database_connection=mysql-connect.html target=_blank class=infotextkey>mysql_connect()($hostname,$username,$password) or die(mysql_error());
mysql_query()("set names 'gbk'");
mysql_select_db($database,$database_connection) or die(mysql_error());
6.连接SQLserver的方法
代码如下:
$dbhost = 'localhost';
$dbuser = 'sa'; //你的mssql用户名
$dbpass = '1234'; //你的mssql密码
$dbname = '0772fang'; //你的mssql库名
$connect=odbc_connect("Driver={SQL Server};Server=$dbhost;Database=$dbname","$dbuser","$dbpass");
$sql="update news_pk set ffnums=ffnums+1 where newsID='$ID'";
$exec=odbc_exec($connect,$sql);