本文目錄一覽:
php 連接資料庫類
我也剛剛學PHP,正在研究中,雖然你只給10分……..
首先,將代碼保存到一個文件,如:mysql.class.php
其次,在一個常用的文件里調用:比如頭部文件header.php,因為我放在根目錄所以用下面方式導入其他文件:
require dirname(__FILE__) . ‘include/config.php’;
//導入類文件
require dirname(__FILE__) . ‘include/mysql.class.php’;
//定義一個類及初始化資料庫類
$db = new mysql($db_host, $db_user, $db_pass, $db_name);
$db_host = $db_user = $db_pass = $db_name = NULL;
然後,在test.php文件調用:
require_once dirname(__FILE__) . ‘/header.php’;
使用方法:
$sql = “讀取表”;
$res = $db-query($sql);
$info = array();//定義數組
while($row=$db-fetchRow($res))
{
$arr[‘id’] = $row[‘id’];
$arr[‘title’] = $row[‘title’];
$info[] = $arr;
}
可以在顯示的地方用:
foreach($info as $i)
{
echo $i[‘title’].”br /”;
}
或是直接使用while
還用另一種調用方式:
$here_area = $db-getRow(“select areaid,areaname from {$table}area where areaid=’$areaid'”);
$here[] = array(‘name’=$here_area[‘areaname’],’id’=$here_area[‘areaid’]);
測試通過,因為我正在使用……………………………….
config.php代碼:
?php
$db_host = “localhost”;
$db_name = “test”;
$db_user = “root”;
$db_pass = “”;
$table = “mini_”;
$charset = “gb2312”;
$dbcharset = “gbk”;
?
mysql.class.php代碼:
?php
class mysql
{
var $link = NULL;
//自動執行__construct php5類構建方法,如果PHP4和PHP5同時使用會自動使用PHP5的方法
function __construct($dbhost, $dbuser, $dbpw, $dbname = ”, $pconnect = 0, $quiet = 0)
{
//自動執行時調用mysql函數
$this-mysql($dbhost, $dbuser, $dbpw, $dbname, $pconnect, $quiet);
}
//php4類構建方法,如果沒有 __construct 就自動執行此功能
function mysql($dbhost, $dbuser, $dbpw, $dbname = ”, $pconnect = 0, $quiet = 0)
{
if ($quiet)
{
$this-connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, $quiet);
}
else
{
$this-settings = array(
‘dbhost’ = $dbhost,
‘dbuser’ = $dbuser,
‘dbpw’ = $dbpw,
‘dbname’ = $dbname,
‘charset’ = $charset,
‘pconnect’ = $pconnect
);
}
}
function connect($dbhost, $dbuser, $dbpw, $dbname = ”, $pconnect = 0, $quiet = 0)
{
global $dbcharset;
if ($pconnect)
{
if (!($this-link = @mysql_pconnect($dbhost, $dbuser, $dbpw)))
{
if (!$quiet)
{
$this-ErrorMsg(“Can’t pConnect MySQL Server($dbhost)!”);
}
return false;
}
}
else
{
if (PHP_VERSION = ‘4.2’)
{
$this-link = @mysql_connect($dbhost, $dbuser, $dbpw, true);
}
else
{
$this-link = @mysql_connect($dbhost, $dbuser, $dbpw);
mt_srand((double)microtime() * 1000000);
}
if (!$this-link)
{
if (!$quiet)
{
$this-ErrorMsg(“Can’t Connect MySQL Server($dbhost)!”);
}
return false;
}
}
$this-dbhash = md5($this-root_path . $dbhost . $dbuser . $dbpw . $dbname);
$this-version = mysql_get_server_info($this-link);
if ($this-version ‘4.1’)
{
if ($dbcharset != ‘latin1’)
{
mysql_query(“SET character_set_connection=$dbcharset, character_set_results=$dbcharset, character_set_client=binary”, $this-link);
}
if ($this-version ‘5.0.1’)
{
mysql_query(“SET sql_mode=””, $this-link);
}
}
if ($dbname)
{
if (mysql_select_db($dbname, $this-link) === false )
{
if (!$quiet)
{
$this-ErrorMsg(“Can’t select MySQL database($dbname)!”);
}
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
function query($sql, $type = ”)
{
if ($this-link === NULL)
{
$this-connect($this-settings[‘dbhost’], $this-settings[‘dbuser’], $this-settings[‘dbpw’], $this-settings[‘dbname’], $this-settings[‘charset’], $this-settings[‘pconnect’]);
$this-settings = array();
}
if ($this-queryCount++ = 99)
{
$this-queryLog[] = $sql;
}
if ($this-queryTime == ”)
{
if (PHP_VERSION = ‘5.0.0’)
{
$this-queryTime = microtime(true);
}
else
{
$this-queryTime = microtime();
}
}
if (!($query = mysql_query($sql, $this-link)) $type != ‘SILENT’)
{
$this-error_message[][‘message’] = ‘MySQL Query Error’;
$this-error_message[][‘sql’] = $sql;
$this-error_message[][‘error’] = mysql_error($this-link);
$this-error_message[][‘errno’] = mysql_errno($this-link);
$this-ErrorMsg();
return false;
}
return $query;
}
function affected_rows()
{
return mysql_affected_rows($this-link);
}
function num_fields($query)
{
return mysql_num_fields($query);
}
function error()
{
return mysql_error($this-link);
}
function errno()
{
return mysql_errno($this-link);
}
function num_rows($query)
{
return mysql_num_rows($query);
}
function insert_id()
{
return mysql_insert_id($this-link);
}
function fetchRow($query)
{
return mysql_fetch_assoc($query);
}
function fetcharray($query)
{
return mysql_fetch_array($query);
}
function version()
{
return $this-version;
}
function close()
{
return mysql_close($this-link);
}
function ErrorMsg($message = ”, $sql = ”)
{
if ($message)
{
echo “$message\n\n”;
}
else
{
echo “bMySQL server error report:”;
print_r($this-error_message);
}
exit;
}
function getCol($sql)
{
$res = $this-query($sql);
if ($res !== false)
{
$arr = array();
while ($row = mysql_fetch_row($res))
{
$arr[] = $row[0];
}
return $arr;
}
else
{
return false;
}
}
function getOne($sql, $limited = false)
{
if ($limited == true)
{
$sql = trim($sql . ‘ LIMIT 1’);
}
$res = $this-query($sql);
if ($res !== false)
{
$row = mysql_fetch_row($res);
if ($row !== false)
{
return $row[0];
}
else
{
return ”;
}
}
else
{
return false;
}
}
function getAll($sql)
{
$res = $this-query($sql);
if ($res !== false)
{
$arr = array();
while ($row = mysql_fetch_assoc($res))
{
$arr[] = $row;
}
return $arr;
}
else
{
return false;
}
}
//使用: getRow($sql,true) 如果有true那值是 limit 1,讀取一條信息
function getRow($sql, $limited = false)
{
if ($limited == true)
{
$sql = trim($sql . ‘ LIMIT 1’);
}
$res = $this-query($sql);
if ($res !== false)
{
return mysql_fetch_assoc($res);
}
else
{
return false;
}
}
}
?
PHp如何連接資料庫?
PHP鏈接資料庫有幾種方式
mysqli:
?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
// 創建連接
$conn = new mysqli($servername, $username, $password);
// 檢測連接
if ($conn-connect_error) {
die(“連接失敗: ” . $conn-connect_error);
}
echo “連接成功”;
?
也可以使用PDO進行鏈接,前提是你必須在php.ini中開啟PDO:
?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
try {
$conn = new PDO(“mysql:host=$servername;dbname=myDB”, $username, $password);
echo “連接成功”;
}
catch(PDOException $e)
{
echo $e-getMessage();
}
?
建議使用PDO,功能更加強大,兼容各種資料庫
怎麼將php與資料庫連接
php鏈接mysql必備條件:
已安裝mysql資料庫;
檢查php環境是否已開啟mysql擴展(一般情況下是開啟的);
檢查方法:a.使用phpinfo();函數,看有沒有mysql項;b.打開php.ini文件,檢查php_mysql.dll前分號是否已取掉。
php鏈接代碼如下:
?php
//設置編碼格式
header(“Content-type:text/html;charset=utf-8”);
//定義資料庫主機地址
$host=”localhost”;
//定義mysql資料庫登錄用戶名
$user=”root”;
//定義mysql資料庫登錄密碼
$pwd=””;
//鏈接資料庫
$conn = mysql_connect($host,$user,$pwd);
//對連接進行判斷
if(!$conn){
die(“資料庫連接失敗!”.mysql_errno());
}else{
echo “資料庫連接成功!”;
}
?
php裡面怎麼鏈接資料庫?
php鏈接mysql必備條件:
已安裝mysql資料庫;
檢查php環境是否已開啟mysql擴展(一般情況下是開啟的);
檢查方法:a.使用phpinfo();函數,看有沒有mysql項;b.打開php.ini文件,檢查php_mysql.dll前分號是否已取掉。
php鏈接代碼如下:
?php
//設置編碼格式
header(“Content-type:text/html;charset=utf-8”);
//定義資料庫主機地址
$host=”localhost”;
//定義mysql資料庫登錄用戶名
$user=”root”;
//定義mysql資料庫登錄密碼
$pwd=””;
//鏈接資料庫
$conn = mysql_connect($host,$user,$pwd);
//對連接進行判斷
if(!$conn){
die(“資料庫連接失敗!”.mysql_errno());
}else{
echo “資料庫連接成功!”;
}
?
PHP連接資料庫的幾種方法
用ASP連接各種資料庫的方法
一、ASP的對象存取資料庫方法
在ASP中,用來存取資料庫的對象統稱ADO(Active Data Objects),主要含有三種對象:Connection、Recordset 、Command
Connection:負責打開或連接數據
Recordset:負責存取數據表
Command:負責對資料庫執行行動查詢命令
二、連接各資料庫的驅動程序
連接各資料庫可以使用驅動程序,也可以使用數據源,不過我建議大家使用驅動程序,因為使用驅動程序非常方便、簡單,而使用數據源比較麻煩。
ODBC鏈接
適合資料庫類型 鏈接方式
access “Driver={microsoft access driver(*.mdb)};dbq=*.mdb;uid=admin;pwd=pass;”
dBase “Driver={microsoft dbase driver(*.dbf)};driverid=277;dbq=————;”
Oracle “Driver={microsoft odbc for oracle};server=oraclesever.world;uid=admin;pwd=pass;”
MSSQL server “Driver={sql server};server=servername;database=dbname;uid=sa;pwd=pass;”
MS text “Driver={microsoft text driver(*.txt; *.csv)};dbq=—–;extensions=asc,csv,tab,txt;Persist SecurityInfo=false;”
Visual Foxpro “Driver={microsoft Visual Foxpro driver};sourcetype=DBC;sourceDB=*.dbc;Exclusive=No;”
MySQL “Driver={mysql};database=yourdatabase;uid=username;pwd=yourpassword;option=16386;”
OLEDB鏈接
適合的資料庫類型 鏈接方式
access “Provider=microsoft.jet.oledb.4.0;data source=your_database_path;user id=admin;password=pass;”
Oracle “Provider=OraOLEDB.Oracle;data source=dbname;user id=admin;password=pass;”
MS SQL Server “Provider=SQLOLEDB;data source=machinename;initial catalog=dbname;userid=sa;password=pass;”
MS text “Provider=microsof.jet.oledb.4.0;data source=your_path;Extended Properties′text;FMT=Delimited′”
而我們在一般情況下使用Access的資料庫比較多,在這裡我建議大家連接Access資料庫使用下面的方法:
dim conn
set conn = server.createobject(“adodb.connection”)
conn.open = “provider=microsoft.jet.oledb.4.0;” “data source = ” server.mappath(“../db/bbs.mdb”)
其中../db/bbs.mdb是你的資料庫存放的相對路徑!如果你的資料庫和ASP文件在同一目錄下,你只要這樣寫就可以了:
dim conn
set conn = server.createobject(“adodb.connection”)
conn.open = “provider=microsoft.jet.oledb.4.0;” “data source = ” server.mappath(“bbs.mdb”)
有許多初學者在遇到資料庫連接時總是會出問題,然而使用上面的驅動程序只要你的資料庫路徑選對了就不會出問題了。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/195799.html