PHP使用ODBC链接access数据库

08. February 2017 PHP 0

<?php
header(“Content-type: text/html; charset=utf-8″); //设置编码
$connstr=”DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=” . realpath(“test.mdb”);//链接access数据库
$connid=odbc_connect($connstr,””,””,SQL_CUR_USE_ODBC);//odbc链接函数

//access默认是中文gb2312编码,php通常使用utf-8编码,在插入和读取中文数字的时候,需要使用一下函数进行编码转换

function utf_gbk($data) { //utf-8编码转gb2312
return iconv(“utf-8″,”gb2312//IGNORE”,”$data”);
}
function gbk_utf($data) { //gb2312转utf-8
return iconv(“gb2312″,”utf-8//IGNORE”,”$data”);
}

$sec=”select * from user”; //查询数据
try {
$result=odbc_exec($connid,$sec);
$data=array();
while ($data[]=odbc_fetch_array($result)) {
}
var_dump($data);
} catch (Exception $e) {
}

$dd=utf_gbk(“赛亚人”); //插入数据库前进行编码转换
$sql=”update user set u_name=’$dd’ where ID=1″;//更新数据
$result=odbc_exec($connid,$sql);
if($result)
echo “successful”;
else
echo “failed”;

$sql=”insert into user(u_name) values(‘lijian’)”;//插入数据库
$result=odbc_exec($connid,$sql);
if($result)
echo “successful”;
else
echo “failed”;

$sql=”delete from user where id=2″;//删除数据
$result=odbc_exec($connid,$sql);
if($result)
echo “successful”;
else
echo “failed”;