class sqlHelper{ \x0d\x0a public $conn; \x0d\x0a public $dbname="數(shù)據(jù)庫(kù)名稱(chēng)"; \x0d\x0a public $username="數(shù)據(jù)庫(kù)用戶(hù)名"; \x0d\x0a public $password="數(shù)據(jù)庫(kù)密碼"; \x0d\x0a public $host="localhost"; \x0d\x0a //連接數(shù)據(jù)庫(kù) \x0d\x0a public function __construct(){ \x0d\x0a $this-conn=mysql_connect($this-host,$this-username,$this-password); \x0d\x0a if(!$this-conn){ \x0d\x0a die("連接失敗".mysql_error()); \x0d\x0a } \x0d\x0a mysql_select_db($this-dbname,$this-conn); \x0d\x0a } \x0d\x0a //執(zhí)行查詢(xún)語(yǔ)句 \x0d\x0a public function execute_dql($sql){ \x0d\x0a $res=mysql_query($sql,$this-conn); \x0d\x0a return $res; \x0d\x0a } \x0d\x0a //執(zhí)行增填改語(yǔ)句 \x0d\x0a public function execute_dml($sql){ \x0d\x0a $b=mysql_query($sql,$this-conn); \x0d\x0a if(!$b){ \x0d\x0a return 3; \x0d\x0a }else{ \x0d\x0a if(mysql_affected_rows($this-conn)){ \x0d\x0a return 1;//表示OK \x0d\x0a }else{ \x0d\x0a return 2;//表示沒(méi)有行收到影響 \x0d\x0a } \x0d\x0a } \x0d\x0a }\x0d\x0a}
成都創(chuàng)新互聯(lián)公司網(wǎng)站建設(shè)服務(wù)商,為中小企業(yè)提供網(wǎng)站制作、網(wǎng)站建設(shè)服務(wù),網(wǎng)站設(shè)計(jì),網(wǎng)站改版維護(hù)等一站式綜合服務(wù)型公司,專(zhuān)業(yè)打造企業(yè)形象網(wǎng)站,讓您在眾多競(jìng)爭(zhēng)對(duì)手中脫穎而出成都創(chuàng)新互聯(lián)公司。
?php
$con = mysql_connect("localhost:3306","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM user");
echo "table border='1'
tr
thUsername/th
thPassword/th
/tr";
while($row = mysql_fetch_array($result)) {
echo "tr";
echo "td" . $row['username'] . "/td";
echo "td" . $row['password'] . "/td";
echo "/tr";
}
echo "/table";
mysql_close($con);
?
從服務(wù)器中獲取用戶(hù)所有信息(SQL SELECT語(yǔ)句)并以表格形式出現(xiàn)
?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
mysql_query("DELETE FROM user WHERE username = '$_POST[username]'");
mysql_close($con);
?
刪除該用戶(hù)所有信息delete.php
?php
$con = mysql_connect("localhost:3306","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql = "INSERT INTO user (username,password)
VALUES
('$_POST[username]','$_POST[password]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?
注冊(cè)一個(gè)新用戶(hù)insert.php
?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
mysql_query("UPDATE user SET password = '$_POST[password]' WHERE username = '$_POST[username]'");
mysql_close($con);
?
修改一個(gè)用戶(hù)密碼update.php
html
head
titleFORM/title
/head
body
br /
h1Insert:/h1
form action="insert.php" method="post"
username:input type="name" name="username"/
br /
password:input type="password" name="password"/
input type="submit" value="submit"/
/form
br /hr /br /
h1Delete/h1
form action="delete.php" method="post"
username:input type="name" name="username" /
br /
Are you sure?input type="submit" value="sure" /
/form
br /hr /br /
h1Update/h1
form action="update.php" method="post"
username:input type="name" name="username"/
br /
You want to change your password into:input type="password" name="password"/
input type="submit" value="submit"/
/form
br /hr /br /
/body
/html
以上三個(gè)功能的提交源Operate.html
先select查詢(xún),返回的結(jié)果顯示到表單中。 在update操作,將在表單中修改的結(jié)果更新到數(shù)據(jù)庫(kù)中。 很容易的,用thinkphp做更容易。
?php
class db{
private $db;
const MYSQL_OPT_READ_TIMEOUT = 11;
const MYSQL_OPT_WRITE_TIMEOUT = 12;
private $tbl_name;
private $where;
private $sort;
private $fields;
private $limit;
public static $_instance = null;
function __construct(){
$cfg = loadConfig('db');
$db = mysqli_init();
$db-options(self::MYSQL_OPT_READ_TIMEOUT, 3);
$db-options(self::MYSQL_OPT_WRITE_TIMEOUT, 1);
@$db-real_connect($cfg['host'],$cfg['user'],$cfg['pwd'],$cfg['db']);
if ($db-connect_error) {
$this-crash($db-errno,$db-error);
}
$db-set_charset("utf8");
$this-db = $db;
//echo $this-db-stat;
}
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self();
}
return self::$_instance;
}
private function __clone() {} //覆蓋__clone()方法,禁止克隆
public function find($conditions = null){
if($conditions) $this-where($conditions);
return $this-getArray($this-buildSql(),1);
}
public function findAll($conditions = null){
if($conditions) $this-where($conditions);
return $this-getArray($this-buildSql());
}
//表
public function t($table){ $this-tbl_name = $table; return $this;}
//條件
public function where($conditions){
$where = '';
if(is_array($conditions)){
$join = array();
foreach( $conditions as $key = $condition ){
$condition = $this-db-real_escape_string($condition);
$join[] = "`{$key}` = '{$condition}'";
}
$where = "WHERE ".join(" AND ",$join);
}else{
if(null != $conditions) $where = "WHERE ".$conditions;
}
$this-where = $where;
return $this;
}
//排序
public function sort($sort){
if(null != $sort) $sort = "ORDER BY {$sort}";
$this-sort = $sort;
return $this;
}
//字段
public function fields($fields){ $this-fields = $fields; return $this; }
public function limit($limit){$this-limit = $limit; return $this;}
private function buildSql(){
$this-fields = empty($this-fields) ? "*" : $this-fields;
$sql = "SELECT {$this-fields} FROM {$this-tbl_name} {$this-where} {$this-sort}";
accessLog('db_access',$sql);
if(null != $this-limit)$sql .= " limit {$this-limit}";
return $sql;
}
/**
* 返回查詢(xún)數(shù)據(jù)
* @param $sql
* @param bool $hasOne
* @return array|bool|mixed
*/
private function getArray($sql,$hasOne = false){
if($this-db-real_query($sql) ){
if ($result = $this-db-use_result()) {
$row = array();
if($hasOne){
$row = $result-fetch_assoc();
}else{
while($d = $result-fetch_assoc()) $row[] = $d;
}
$result-close();
$this-fields = "*";
return $row;
}else{
return false;
}
}else{
if($this-db-error){
$this-crash($this-db-errno,$this-db-error,$sql);
}
}
}
public function findSql($sql,$hasOne = false){
accessLog('db_access',$sql);
if($this-db-real_query($sql) ){
if ($result = $this-db-use_result()) {
$row = array();
if($hasOne){
$row = $result-fetch_assoc();
}else{
while($d = $result-fetch_assoc()) $row[] = $d;
}
$result-close();
$this-fields = "*";
return $row;
}else{
return false;
}
}else{
if($this-db-error){
$this-crash($this-db-errno,$this-db-error,$sql);
}
}
}
public function create($row){
if(!is_array($row))return FALSE;
$row = $this-prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key = $value){
$cols[] = '`'.$key.'`';
$vals[] = "'".$this-db-real_escape_string($value)."'";
}
$col = implode(',', $cols);
$val = implode(',', $vals);
$sql = "INSERT INTO `{$this-tbl_name}` ({$col}) VALUES ({$val})";
accessLog('db_access',$sql);
if( FALSE != $this-db-query($sql) ){ // 獲取當(dāng)前新增的ID
if($this-db-insert_id){
return $this-db-insert_id;
}
if($this-db-affected_rows){
return true;
}
}
return FALSE;
}
//直接執(zhí)行sql
public function runSql($sql){
accessLog('db_access',$sql);
if( FALSE != $this-db-query($sql) ){ // 獲取當(dāng)前新增的ID
return true;
}else{
return false;
}
}
public function update($row){
$where = "";
$row = $this-prepera_format($row);
if(empty($row))return FALSE;
foreach($row as $key = $value){
$value = $this-db-real_escape_string($value);
$vals[] = "`{$key}` = '{$value}'";
}
$values = join(", ",$vals);
$sql = "UPDATE {$this-tbl_name} SET {$values} {$this-where}";
accessLog('db_access',$sql);
if( FALSE != $this-db-query($sql) ){ // 獲取當(dāng)前新增的ID
if( $this-db-affected_rows){
return true;
}
}
return false;
}
function delete(){
$sql = "DELETE FROM {$this-tbl_name} {$this-where}";
if( FALSE != $this-db-query($sql) ){ // 獲取當(dāng)前新增的ID
if( $this-db-affected_rows){
return true;
}
}
return FALSE;
}
private function prepera_format($rows){
$columns = $this-getArray("DESCRIBE {$this-tbl_name}");
$newcol = array();
foreach( $columns as $col ){
$newcol[$col['Field']] = $col['Field'];
}
return array_intersect_key($rows,$newcol);
}
//崩潰信息
private function crash($number,$message,$sql=''){
$msg = 'Db Error '.$number.':'.$message ;
if(empty($sql)){
echo t('db_crash');
}else{
$msg .= " SQL:".$sql;
echo t('db_query_err');
}
accessLog('db_error',$msg);
exit;
}
}
php有專(zhuān)門(mén)的sql server操作函數(shù),舉個(gè)簡(jiǎn)單的例子,是查詢(xún)的
$serverName?=?"localhost";?//數(shù)據(jù)庫(kù)服務(wù)器地址
$uid?=?"root";?//數(shù)據(jù)庫(kù)用戶(hù)名
$pwd?=?"123456";?//數(shù)據(jù)庫(kù)密碼
$connectionInfo?=?array("UID"=$uid,?"PWD"=$pwd,?"Database"='databasename');
$conn?=?sqlsrv_connect(?$serverName,?$connectionInfo);
if(?$conn?==?false){
echo?"連接數(shù)據(jù)庫(kù)失??!";
die(?print_r(?sqlsrv_errors(),?true));
}
$sql?=?"select?*?from?user";
$query?=?sqlsrv_query(?$conn,?$sql?,?array(),?array(?"Scrollable"?=?SQLSRV_CURSOR_KEYSET?));
$num_rows?=?sqlsrv_num_rows($query);
if($num_rows??0){
while?($row?=?sqlsrv_fetch_array($query)){
echo?$row['aaaa'];
}
}
其它的操作也同理,舉一反三
phpcms v9是基于mvc模式開(kāi)發(fā)的,所以我們按照其套路到模型層程序中去找就行。在/phpcms/model目錄下存放著與數(shù)據(jù)表名稱(chēng)一致的模型成文件,隨意打開(kāi)一個(gè),你會(huì)看到都繼承了model這個(gè)類(lèi),那么找到它,路徑:/phpcms/libs/classes/model.class.php。對(duì)于數(shù)據(jù)庫(kù)的增刪改查方法都在這里面了,列舉如下:
insert() 增加數(shù)據(jù)、delete()刪除指定條件數(shù)據(jù)、listinfo()讀取支持翻頁(yè)的多條數(shù)據(jù)、select()讀取多條數(shù)據(jù)、update()更新數(shù)據(jù)。
當(dāng)然,還有很多方法,以及各方法的傳參各代表什么意義都有詳細(xì)的注釋看看就會(huì)明白的。
那么我們?cè)诳刂破髦袘?yīng)該如何引入一個(gè)數(shù)據(jù)表的model并對(duì)其進(jìn)行數(shù)據(jù)操作呢,例如我在首頁(yè)控制器中獲取最近注冊(cè)的10個(gè)會(huì)員賬號(hào)信息,可以這么寫(xiě):
$member_db?=?pc_base::load_model("members_model");
!--使用pc_base的load_model方法進(jìn)行加載指定的數(shù)據(jù)表模型,感覺(jué)像TP3.2里的M()函數(shù)--
$member_list?=?$member_db-select(array('islock'=0),"*",10,"id?desc");
!--使用對(duì)應(yīng)的方法獲取數(shù)據(jù)--
就演示到這里吧,如果有mvc架構(gòu)基礎(chǔ)應(yīng)該一看就懂的,更多的關(guān)于phpcms的二次開(kāi)發(fā)深入可以參考官方開(kāi)發(fā)手冊(cè)、代碼中的注釋說(shuō)明以及iphpcms里的二次開(kāi)發(fā)視頻教程。