㈠ php怎麼用mysqli鏈接資料庫和輸出sql
一、mysql與mysqli的概念相關:
1、mysql與mysqli都是php方面的函數集,與
mysql資料庫
關聯不大。
2、在
php5
版本之前,一般是用php的
mysql函數
去驅動mysql資料庫的,比如mysql_query()的函數,屬於
面向過程
3、在php5版本以後,增加了mysqli的函數功能,某種意義上講,它是mysql系統函數的增強版,更穩定更高效更安全,與mysql_query()對應的有mysqli_query(),屬於面向對象,用對象的方式操作驅動mysql資料庫
二、mysql與mysqli的區別:
1、mysql是非持繼連接函數,mysql每次鏈接都會打開一個連接的進程。
2、mysqli是永遠連接函數,mysqli多次運行mysqli將使用同一連接進程,從而減少了伺服器的開銷。mysqli封裝了諸如事務等一些高級操作,同時封裝了DB操作過程中的很多可用的方法。
三、mysql與mysqli的用法:
1:mysql(過程方式):
$conn
=
mysql_connect('
localhost
',
'user',
'password');//連接mysql資料庫
mysql_select_db
('data_base');
//選擇資料庫$result
=
mysql_query('select
*
from
data_base');//第二個可選參數,指定打開的連接$row
=
mysql_fetch_row(
$result
)
)
//只取一行數據echo
$row[0];
//輸出第一個欄位的值
PS:mysqli以過程式的方式操作,有些函數必須指定資源,比如mysqli_query(資源標識,
SQL語句
),並且資源標識的參數是放在前面的,而mysql_query(SQL語句,'資源標識')的資源標識是可選的,默認值是上一個打開的連接或資源。
2、mysqli(對象方式):
$conn
=
new
mysqli('localhost',
'user',
'password','data_base');//要使用new
操作符
,最後一個參數是直接指定資料庫//假如構造時候不指定,那下一句需要$conn
->
select_db('data_base')實現$result
=
$conn
->
query(
'select
*
from
data_base'
);$row
=
$result
->
fetch_row();
//取一行數據echo
row[0];
//輸出第一個欄位的值
使用new
mysqli('localhost',
usenamer',
'password',
'databasename');會報錯,提示如下:
Fatal
error:
Class
'mysqli'
not
found
in
...
一般是mysqli是沒有開啟的,因為mysqli類不是
默認開啟
的,win下要改php.ini,去掉php_mysqli.dll前的;,linux下要把mysqli編譯進去。
四、mysql_connect()與mysqli_connect()
1.使用mysqli,可以把資料庫名稱當作參數傳給mysqli_connect()函數,也可以傳遞給mysqli的
構造函數
;
2.如果調用mysqli_query()或mysqli的對象查詢query()方法,則連接標識是必需的。
㈡ 如何使用php登錄mysql,使用mysqli的登錄方式,並插入一條數據,誰有有完整的php原代碼
本文所述的是一個在PHP中以mysqli方式連接資料庫的一個資料庫類實例,該資料庫類是從一個PHP的CMS中整理出來的,可實現PHP連接資料庫類,MySQLi版,兼容PHP4,對於有針對性需要的朋友可根據此代碼進行優化和修改。
?
<?php
#==================================================================================================
# Filename: /db/db_mysqli.php
# Note : 連接資料庫類,MySQLi版
#==================================================================================================
#[類庫sql]
class db_mysqli
{
var $query_count = 0;
var $host;
var $user;
var $pass;
var $data;
var $conn;
var $result;
var $prefix = "qinggan_";
//返回結果集類型,默認是數字+字元
var $rs_type = MYSQLI_ASSOC;
var $query_times = 0;#[查詢時間]
var $conn_times = 0;#[連接資料庫時間]
var $unbuffered = false;
//定義查詢列表
var $querylist;
var $debug = false;
#[構造函數]
function __construct($config=array())
{
$this->host = $config['host'] ? $config['host'] : 'localhost';
$this->port = $config['port'] ? $config['port'] : '3306';
$this->user = $config['user'] ? $config['user'] : 'root';
$this->pass = $config['pass'] ? $config['pass'] : '';
$this->data = $config['data'] ? $config['data'] : '';
$this->debug = $config["debug"] ? $config["debug"] : false;
$this->prefix = $config['prefix'] ? $config['prefix'] : 'qinggan_';
if($this->data)
{
$ifconnect = $this->connect($this->data);
if(!$ifconnect)
{
$this->conn = false;
return false;
}
}
return true;
}
#[兼容PHP4]
function db_mysqli($config=array())
{
return $this->__construct($config);
}
#[連接資料庫]
function connect($database="")
{
$start_time = $this->time_used();
if(!$this->port) $this->port = "3306";
$this->conn = @mysqli_connect($this->host,$this->user,$this->pass,"",$this->port) or false;
if(!$this->conn)
{
return false;
}
$version = $this->get_version();
if($version>"4.1")
{
mysqli_query($this->conn,"SET NAMES 'utf8'");
if($version>"5.0.1")
{
mysqli_query($this->conn,"SET sql_mode=''");
}
}
$end_time = $this->time_used();
$this->conn_times += round($end_time - $start_time,5);#[連接資料庫的時間]
$ifok = $this->select_db($database);
return $ifok ? true : false;
}
function select_db($data="")
{
$database = $data ? $data : $this->data;
if(!$database)
{
return false;
}
$this->data = $database;
$start_time = $this->time_used();
$ifok = mysqli_select_db($this->conn,$database);
if(!$ifok)
{
return false;
}
$end_time = $this->time_used();
$this->conn_times += round($end_time - $start_time,5);#[連接資料庫的時間]
return true;
}
#[關閉資料庫連接,當您使用持續連接時該功能失效]
function close()
{
if(is_resource($this->conn))
{
return mysqli_close($this->conn);
}
else
{
return true;
}
}
function __destruct()
{
return $this->close();
}
function set($name,$value)
{
if($name == "rs_type")
{
$value = strtolower($value) == "num" ? MYSQLI_NUM : MYSQLI_ASSOC;
}
$this->$name = $value;
}
function query($sql)
{
if(!is_resource($this->conn))
{
$this->connect();
}
else
{
if(!mysql_ping($this->conn))
{
$this->close();
$this->connect();
}
}
if($this->debug)
{
$sqlkey = md5($sql);
if($this->querylist)
{
$qlist = array_keys($this->querylist);
if(in_array($sqlkey,$qlist))
{
$count = $this->querylist[$sqlkey]["count"] + 1;
$this->querylist[$sqlkey] = array("sql"=>$sql,"count"=>$count);
}else{
$this->querylist[$sqlkey] = array("sql"=>$sql,"count"=>1);
}
}
else{
$this->querylist[$sqlkey] = array("sql"=>$sql,"count"=>1);
}
}
$start_time = $this->time_used();
$func = $this->unbuffered && function_exists("mysqli_multi_query") ? "mysqli_multi_query" : "mysqli_query";
$this->result = @$func($this->conn,$sql);
$this->query_count++;
$end_time = $this->time_used();
$this->query_times += round($end_time - $start_time,5);#[查詢時間]
if(!$this->result)
{
return false;
}
return $this->result;
}
function get_all($sql="",$primary="")
{
$result = $sql ? $this->query($sql) : $this->result;
if(!$result)
{
return false;
}
$start_time = $this->time_used();
$rs = array();
$is_rs = false;
while($rows = mysqli_fetch_array($result,$this->rs_type))
{
if($primary && $rows[$primary])
{
$rs[$rows[$primary]] = $rows;
}
else
{
$rs[] = $rows;
}
$is_rs = true;
}
$end_time = $this->time_used();
$this->query_times += round($end_time - $start_time,5);#[查詢時間]
return ($is_rs ? $rs : false);
}
function get_one($sql="")
{
$start_time = $this->time_used();
$result = $sql ? $this->query($sql) : $this->result;
if(!$result)
{
return false;
}
$rows = mysqli_fetch_array($result,$this->rs_type);
$end_time = $this->time_used();
$this->query_times += round($end_time - $start_time,5);#[查詢時間]
return $rows;
}
function insert_id($sql="")
{
if($sql)
{
$rs = $this->get_one($sql);
return $rs;
}
else
{
return mysqli_insert_id($this->conn);
}
}
function insert($sql)
{
$this->result = $this->query($sql);
$id = $this->insert_id();
return $id;
}
function all_array($table,$condition="",$orderby="")
{
if(!$table)
{
return false;
}
$table = $this->prefix.$table;
$sql = "SELECT * FROM ".$table;
if($condition && is_array($condition) && count($condition)>0)
{
$sql_fields = array();
foreach($condition AS $key=>$value)
{
$sql_fields[] = "`".$key."`='".$value."' ";
}
$sql .= " WHERE ".implode(" AND ",$sql_fields);
}
if($orderby)
{
$sql .= " ORDER BY ".$orderby;
}
$rslist = $this->get_all($sql);
return $rslist;
}
function one_array($table,$condition="")
{
if(!$table)
{
return false;
}
$table = $this->prefix.$table;
$sql = "SELECT * FROM ".$table;
if($condition && is_array($condition) && count($condition)>0)
{
$sql_fields = array();
foreach($condition AS $key=>$value)
{
$sql_fields[] = "`".$key."`='".$value."' ";
}
$sql .= " WHERE ".implode(" AND ",$sql_fields);
}
$rslist = $this->get_one($sql);
return $rslist;
}
//將數組寫入數據中
function insert_array($data,$table,$insert_type="insert")
{
if(!$table || !is_array($data) || !$data)
{
return false;
}
$table = $this->prefix.$table;//自動增加表前綴
if($insert_type == "insert")
{
$sql = "INSERT INTO ".$table;
}
else
{
$sql = "REPLACE INTO ".$table;
}
$sql_fields = array();
$sql_val = array();
foreach($data AS $key=>$value)
{
$sql_fields[] = "`".$key."`";
$sql_val[] = "'".$value."'";
}
$sql.= "(".(implode(",",$sql_fields)).") VALUES(".(implode(",",$sql_val)).")";
return $this->insert($sql);
}
//更新數據
function update_array($data,$table,$condition)
{
if(!$data || !$table || !$condition || !is_array($data) || !is_array($condition))
{
return false;
}
$table = $this->prefix.$table;//自動增加表前綴
$sql = "UPDATE ".$table." SET ";
$sql_fields = array();
foreach($data AS $key=>$value)
{
$sql_fields[] = "`".$key."`='".$value."'";
}
$sql.= implode(",",$sql_fields);
$sql_fields = array();
foreach($condition AS $key=>$value)
{
$sql_fields[] = "`".$key."`='".$value."' ";
}
$sql .= " WHERE ".implode(" AND ",$sql_fields);
return $this->query($sql);
}
function count($sql="")
{
if($sql)
{
$this->rs_type = MYSQLI_NUM;
$this->query($sql);
$rs = $this->get_one();
$this->rs_type = MYSQLI_ASSOC;
return $rs[0];
}
else
{
return mysqli_num_rows($this->result);
}
}
function num_fields($sql="")
{
if($sql)
{
$this->query($sql);
}
return mysqli_num_fields($this->result);
}
function list_fields($table)
{
$rs = $this->get_all("SHOW COLUMNS FROM ".$table);
if(!$rs)
{
return false;
}
foreach($rs AS $key=>$value)
{
$rslist[] = $value["Field"];
}
return $rslist;
}
#[顯示表名]
function list_tables()
{
$rs = $this->get_all("SHOW TABLES");
return $rs;
}
function table_name($table_list,$i)
{
return $table_list[$i];
}
function escape_string($char)
{
if(!$char)
{
return false;
}
return mysqli_escape_string($this->conn,$char);
}
function get_version()
{
return mysqli_get_server_info($this->conn);
}
function time_used()
{
$time = explode(" ",microtime());
$used_time = $time[0] + $time[1];
return $used_time;
}
//Mysql的查詢時間
function conn_times()
{
return $this->conn_times + $this->query_times;
}
//MySQL查詢資料
function conn_count()
{
return $this->query_count;
}
# 高效SQL生成查詢,僅適合單表查詢
function phpok_one($tbl,$condition="",$fields="*")
{
$sql = "SELECT ".$fields." FROM ".$this->db->prefix.$tbl;
if($condition)
{
$sql .= " WHERE ".$condition;
}
return $this->get_one($sql);
}
function debug()
{
if(!$this->querylist || !is_array($this->querylist) || count($this->querylist) < 1)
{
return false;
}
$html = '<table cellpadding="0" cellspacing="0" width="100%" bgcolor="#CECECE"><tr><td>';
$html.= '<table cellpadding="1" cellspacing="1" width="100%">';
$html.= '<tr><th bgcolor="#EFEFEF" height="30px">SQL</th><th bgcolor="#EFEFEF" width="80px">查詢</th></tr>';
foreach($this->querylist AS $key=>$value)
{
$html .= '<tr><td bgcolor="#FFFFFF"><div style="padding:3px;color:#6E6E6E;">'.$value['sql'].'</div></td>';
$html .= '<td align="center" bgcolor="#FFFFFF"><div style="padding:3px;color:#000000;">'.$value["count"].'</div></td></tr>';
}
$html.= "</table>";
$html.= "</td></tr></table>";
return $html;
}
function conn_status()
{
if(!$this->conn) return false;
return true;
}
}
?>
㈢ 如何在php中鏈接mysql資料庫
用mysqli擴展庫
<?php
//資料庫主機
$db_host='localhost';
//資料庫用戶名
$db_user='root';
//資料庫密碼
$db_pwd='root';
//資料庫名稱
$db_name='test';
$mysqli=newMysqli($db_host,$db_user,$db_pwd,$db_name);
if(mysqli_connect_error()){
echo"connecterror";
}else{
echo"connectsuccess";
}
//關閉連接
$mysqli->close();
㈣ 如何在php中擴展mysqli插件。
Mysqli是php5之後才有的功能,沒有開啟擴展的可以打開php.ini的配置文件
查找下面的語句:;extension=php_mysqli.dll將其修改為:extension=php_mysqli.dll即可。
相對於mysql有很多新的特性和優勢
(1)支持本地綁定、准備(prepare)等語法
(2)執行sql語句的錯誤代碼
(3)同時執行多個sql
(4)另外提供了面向對象的調用介面的方法。
㈤ php中mysqli處理查詢結果集的幾個方法
$sql="select * from user"; $result=$link->query($sql); $row=$result->fetch_all(MYSQLI_BOTH);//參數MYSQL_ASSOC、MYSQLI_NUM、MYSQLI_BOTH規定產生數組類型
$n=0; while($n<mysqli_num_rows($result)){ echo "ID:".$row[$n]["id"]."用戶名:".$row[$n]["name"]."密碼:".$row[$n]["password"]."<br />"; $n++;
}
㈥ php使用mysqli和pdo擴展,測試對比mysql資料庫的執行效率完整示例
本文實例講述了php使用mysqli和pdo擴展,測試對比mysql資料庫的執行效率。分享給大家供大家參考,具體如下:
<?php
/**
*
測試pdo和mysqli的執行效率
*/
header("Content-type:text/html;charset=utf-8");
//通過pdo鏈接資料庫
$pdo_startTime
=
microtime(true);
$pdo
=
new
PDO("mysql:host=localhost;dbname=test","root","1234",array(PDO::MYSQL_ATTR_INIT_COMMAND
=>
"SET
NAMES'utf8';"));
for($i=1;$i<=100;$i++){
$title
=
"pdo標題".$i;
$content
=
"pdo內容".$i;
$addtime
=
time();
$user_id
=
$i;
$pdo_sql
=
"INSERT
INTO
`article`(`title`,`content`,`addtime`,`user_id`)
VALUES(:title,:content,:addtime,:user_id)";
$sth
=
$pdo->prepare($pdo_sql);
$sth->bindParam(':title',$title);
$sth->bindParam(':content',$content);
$sth->bindParam(':addtime',$addtime);
$sth->bindParam(':user_id',$user_id);
$sth->execute();
}
$pdo_endTime
=
microtime(true);
$pdo_time
=
$pdo_endTime
-
$pdo_startTime;
echo
$pdo_time;
echo
"<hr/>";
//通過mysql鏈接資料庫
$mysqli_startTime
=
microtime(true);
$mysqli
=
mysqli_connect("localhost","root","1234","test")
or
die("數據連接失敗");
mysqli_query($mysqli,"set
names
utf8");
for($i=1;$i<=100;$i++){
$title
=
"mysqli標題".$i;
$content
=
"mysqli內容".$i;
$addtime
=
time();
$user_id
=
$i;
$sql
=
"INSERT
INTO
`article`(`title`,`content`,`addtime`,`user_id`)
VALUES('".$title."','".$content."',".$addtime.",".$user_id.")";
mysqli_query($mysqli,$sql);
}
$mysqli_endTime
=
microtime(true);
$mysqli_time
=
$mysqli_endTime
-
$mysqli_startTime;
echo
$mysqli_time;
echo
"<hr/>";
if($pdo_time
>
$mysqli_time){
echo
"pdo的執行時間是mysqli的".round($pdo_time/$mysqli_time)."倍";
}else{
echo
"mysqli的執行時間是pdo的".round($mysqli_time/$pdo_time)."倍";
}
測試結果:其實經過多次測試,pdo和mysqli的執行效率差不多。
更多關於PHP相關內容感興趣的讀者可查看本站專題:《PHP基於pdo操作資料庫技巧總結》、《php+mysqli資料庫程序設計技巧總結》、《php面向對象程序設計入門教程》、《php字元串(string)用法總結》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:php使用mysqli和pdo擴展,測試對比連接mysql資料庫的效率完整示例php中資料庫連接方式pdo和mysqli對比分析php中關於mysqli和mysql區別的一些知識點分析php操作mysqli(示例代碼)php封裝的mysqli類完整實例PHP以mysqli方式連接類完整代碼實例php簡單解析mysqli查詢結果的方法(2種方法)php中mysql連接方式PDO使用詳解Php中用PDO查詢Mysql來避免SQL注入風險的方法php
mysql
PDO
查詢操作的實例詳解PHP實現PDO的mysql資料庫操作類
㈦ 如何在php安裝完成之後加入mysqli支持
修改php安裝目錄裡面的 php.ini 文件,用記事本打開,Ctrl+f鍵查找下面這一行
找到後把下面這一行前面的分號去掉。重啟伺服器即可。
;extension=php_mysqli.dll
㈧ 騰訊雲伺服器下,怎麼安裝php的mysqli擴展
添加擴展的基本步驟:
1、進入php源代碼目錄:# cd /tmp/php-5.x.x/
2、再進入要添加的mysqli擴展源碼目錄:# cd ext/mysqli/
2、調用已經編譯好的php裡面的phpize:# /usr/local/php/bin/phpize
3、然後configure:# ./configure --with-php-config=/usr/local/php/bin/php-config --with-mysqli=/usr/local/mysql/bin/mysql_config
(/usr/local/mysql 為mysql的安裝目錄)
4、make && make install
5、編譯之後,自動把mysqli.so放到了默認的php擴展目錄下,我的為 /usr/local/php/lib/php/extensions/no-debug-non-zts-20xx0722/
(phpinfo可查看或者執行命令/usr/local/php/bin/php-config --extension-dir )
再修改php.ini 找到extension_dir 默認路徑為 extension_dir="./" 我修改後才啟動載入的
在下面添加extension = "mysqli.so" 保存即可
extension_dir="/usr/local/php/lib/php/extensions/no-debug-non-zts-20xx0722/"
extension = "mysqli.so"
6、重啟apache:# service httpd restart
求課吧有挺多IT編程類的教程的
㈨ linux下的php到底是怎麼載入mysqli模塊的
添加擴展的基本步驟:
1、進入PHP源代碼目錄:# cd /tmp/php-5.2.14/
2、再進入要添加的mysqli擴展源碼目錄:# cd ext/mysqli/
2、調用已經編譯好的php裡面的phpize:# /usr/local/php/bin/phpize
3、然後configure:# ./configure --with-php-config=/usr/local/php/bin/php-config --with-mysqli=/usr/local/MySQL/bin/mysql_config
(/usr/local/mysql 為mysql的安裝目錄)
4、make && make install
5、編譯之後,自動把mysqli.so放到了默認的php擴展目錄下,我的為 /usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/
(phpinfo可查看或者執行命令/usr/local/php/bin/php-config --extension-dir )
再修改php.ini 找到extension_dir 默認路徑為 extension_dir="./" 我修改後才啟動載入的
在下面添加extension = "mysqli.so" 保存即可
extension_dir="/usr/local/php/lib/php/extensions/no-debug-non-zts-20060613/"
extension = "mysqli.so"
6、重啟apache:# service httpd restart
㈩ PHP使用mysqli擴展連接MySQL資料庫
1.面向對象的使用方式
$db
=
new
mysqli('localhost',
'root',
'123456',
'dbname');
如果建立連接時未指定資料庫則選擇使用的資料庫,切換使用的資料庫
$db->select_db('dbname');
$query
=
"SELECT
*
FROM
user
WHERE
uid=4";
$result
=
$db->query($query);
$result_num
=
$result->num_rows;
$row
=
$result->fetch_assoc();
//返回一個關聯數組,可以通過$row['uid']的方式取得值
$row
=
$result->fetch_row();
//返回一個列舉數組,可以通過$row[0]的方式取得值
$row
=
$result->fetch_array();
//返回一個混合數組,可以通過$row['uid']和$row[0]兩種方式取得值
$row
=
$result->fetch_object();
//返回一個對象,可以通過$row->uid的方式取得值
$result->free();
//釋放結果集
$db->close();
//關閉一個資料庫連接,這不是必要的,因為腳本執行完畢時會自動關閉連接
當進行INSERT、UPDATE、DELETE操作時,使用$db->affected_rows查看影響行數
2.面向過程的使用方式
$db
=
mysqli_connect('localhost',
'root',
'123456',
'dbname');
如果建立連接時未指定資料庫則選擇使用的資料庫,切換使用的資料庫
mysqli_select_db($db,
'dbname');
查詢資料庫
$query
=
"SELECT
*
FROM
user
WHERE
uid=4";
$result
=
mysqli_query($db,
$query);
$result_num
=
mysqli_num_rows($result);
返回一行結果
$row
=
mysqli_fetch_assoc($result);
//返回一個關聯數組,可以通過$row['uid']的方式取得值
$row
=
mysqli_fetch_row($result);
//返回一個列舉數組,可以通過$row[0]的方式取得值
$row
=
mysqli_fetch_array($result);
//返回一個混合數組,可以通過$row['uid']和$row[0]兩種方式取得值
$row
=
mysqli_fetch_object($result);
//返回一個對象,可以通過$row->uid的方式取得值
斷開資料庫連接
mysqli_free_result($result);
//釋放結果集
mysqli_close($db);
//關閉一個資料庫連接,這不是必要的,因為腳本執行完畢時會自動關閉連接
當進行INSERT、UPDATE、DELETE操作時,使用mysqli_affected_rows()查看影響行數