1. php怎么连接mysql数据库
php连接mysql 分为面向过程和面向对象的。
以下三种方式都可以连接
一 MySQLi - 面向对象
<?php
$servername="localhost";
$username="username";
$password="password";
//创建连接$conn=newmysqli($servername,$username,$password);
//检测连接if($conn->connect_error){
die("连接失败:".$conn->connect_error);}echo"连接成功";
?>
二 MySQLi - 面向过程
<?php
$servername="localhost";
$username="username";
$password="password";
//创建连接$conn=mysqli_connect($servername,$username,$password);
//检测连接if(!$conn){
die("Connectionfailed:".mysqli_connect_error());}echo"连接成功";
?>
三 PDO方式
<?php
$servername="localhost";
$username="username";
$password="password";
try{
$conn=newPDO("mysql:host=$servername;dbname=myDB",$username,$password);
echo"连接成功";
}catch(PDOException$e){
echo$e->getMessage();
}
?>
连接在脚本执行完后会自动关闭。你也可以使用以下代码来关闭连接:
MySQLi - 面向对象
$conn->close();
MySQLi - 面向过程
mysqli_close($conn);
PDO
$conn = null;
2. PHP + Mysql多个表并行查询如何实现
在PHP-FPM处理HTTP请求时,有时会遇到一个请求需要进行多次MySQL查询(在报表类应用中比较常见)。通常我们会以串行方式查询:
$link=newmysqli();
$rs1=$link->query('SELECT*FROMtable1');
while($row=$rs1->fetch_row()){...}
$rs2=$link->query('SELECT*FROMtable2');
while($row=$rs2->fetch_row()){...}
$rs3=$link->query('SELECT*FROMtable3');
while($row=$rs3->fetch_row()){...}
串行查询方式有个缺点:在MySQL返回数据之前,PHP一直是处于空等的状态,不会继续往后执行。如果数据量大或者查询复杂,MySQL响应可能会比较慢,那么以串行方式查询会有一些延迟。给用户最直接的感受就是 Loading… 的圈圈一直打转。
那么有什么办法可以减少查询MySQL的时间?用多进程并行查询不行,因为PHP-FPM 中不允许用 pcntl_fork 一类的调用。
幸好还有 mysqlnd,mysqlnd提供了类似 stream_select 的机制(见 这篇文章) ,可以做到在单进程中对MySQL并行查询。这主要运用了mysqli_poll 和 reap_async_query 两个函数。
还是通过例子来介绍MySQL并行查询的实施方法。假设要并行地向MySQL发出10个查询,最基本的代码应该是这样的:
1.$links=[];
2.for($i=0;$i!==10;$i++){
3.$links[$i]=newmysqli('127.0.0.1','user','password','db1');
4.$links[$i]->query('SELECTSLEEP(1)',MYSQLI_ASYNC);
5.}
6.$allResult=[];
7.while(!empty($links)){
8.$reads=$links;
9.$errors=$reject=[];
10.if(!mysqli_poll($reads,$errors,$reject,null)){
11.continue;
12.}
13.foreach($readsas$read){
14.$idx=array_search($read,$links,true);
15.$allResult[$idx]=[];
16.$result=$read->reap_async_query();
17.while($row=$result->fetch_row()){
18.$allResult[$idx][]=$row;
19.}
20.$read->close();
21.unset($links[$idx]);
22.}
23.}
解释下这段代码的含义:
2~5行,同时发起10个MySQL连接,并发出查询
注意query() 的第二个参数带上了 MYSQLI_ASYNC 表示非阻塞查询
10行,使用mysqli_poll 轮询10个连接的查询有无返回
mysqli_poll 的第一个参数$reads是个数组,包含需要轮询那些连接。mysqli_poll 执行完后,会改写$reads,改写后$reads包含的是那些已经有数据返回连接。
mysqli_poll的第四个参数,控制的是轮询的等待时间,单位是“秒”。如果像本例当中设置为null,那么mysqli_poll轮询是阻塞的:只有监听的连接中,任意一个连接有数据返回了,mysqli_poll才会返回。如果等待时间设置为0,那么每次执行mysqli_poll会立即返回,外层的while会频繁循环。
第11~19行,遍历已经有数据返回的连接
reap_async_query和普通query一样,返回的是mysqli_result,可以一行行fetch数据
20~21行,对于已经获得了数据的连接,下次mysqli_poll就不需要再轮询这个连接了,所以关闭连接,并从$links数组删除这个连接
当所有的连接都返回了数据,$links数组空了,while循环也就终止了。
使用并行查询的方式,可以大大缩短处理HTTP请求的时间,假设本例中的10个SQL查询,每个需要执行1秒。因为是并行,处理所有的查询,也只需要1秒左右。
3. PHP中MySQLi和MySQL是一回事吗
mysql与mysqli都是php方面的函数集,与mysql数据库关联不大。
在php5版本以后,增加了mysqli的函数功能,某种意义上讲,它是mysql系统函数的增强版
4. 关于php中mysql mysqli 区别
PHP中mysql有两个概念,一个是mysql数据库,一个是用于操作mysql数据库的扩展(PHP的各种功能都是通过这些底层扩展来实现的)。而你这个问题中的mysql,就指的是扩展。
PHP5开始有了mysqli,按照PHP官方描述,它是mysql增强版扩展。事实上它确实更搞笑更安全,并推荐大家使用。到PHP5.3的时候,原来的mysql扩展已经被标注为过时。而到了PHP7,原mysql扩展被彻底废弃。
所以不管是否使用PHP7,都建议使用mysqli或pdo扩展来操作mysql数据库。
另外,mysqli并不是简单的在原来mysql的方法上加一个i,它是自己一套方法。mysqli同时支持面向过程和面向对象的方式,强烈建议你学者使用面向对象的方式。
5. php mysql与mysqli 区别
1、mysql是非持继连接函数,mysql每次链接都会打开一个连接的进程。
2、mysqli是永远连接函数,mysqli多次运行mysqli将使用同一连接进程,从而减少了服务器的开销。mysqli封装了诸如事务等一些高级操作,同时封装了DB操作过程中的很多可用的方法。
mysqli连接是永久连接,而mysql是非永久连接。
mysql连接:每当第二次使用的时候,都会重新打开一个新的进程。
mysqli连接:一直都只使用同一个进程。
6. PHP mysql数据库问题
1. mysql操作语句环境有两种,1种是函数形式的,如mysql_query,另一种是面向对象形式的如$mysqli = new Mysqli($host,$username,$pwd);,第二种所有操作都是以php 面向对象的形式操作mysql数据库的。如mysqli->query('sql');等同于mysql_qeury('sql')
查看服务器是否开启mysqli扩展的方式可以通过<?php echo phpinfo() ?>看是否存在mysqli扩展
2.获取插入数据的id方法是mysql_insert_id($query);获取mysqli->insert_id;要获取插入数据id,id必须设置为自动增加模式(auto_increment).
$msyqli = new Mysqli($host,$user,$pwd);
$mysqli->select_db($dbname);
$mysqli->query('set names gbk');
$mysqli->query('insert into tb123(body)values("test")');
echo $mysql->insert_id;
$mysqli->close();
最后,请给点分数,奖励一下啊
7. PHP7.0怎么通过打开扩展功能和mysql相连
第一步:进入php源码中的"ext/mysql"目录下
第二步:在当前目录下运行phpize命令:/usr/local/php524/bin/phpize
phpize的规则:去哪个目录下运行phpize文件,那么就会在该目录下生成一个configure文件。
第三步:运行刚才生成的configure文件
命令: ./configure --with-php-config=/usr/local/php524/bin/php-config --with-mysql=/usr/local/mysql/
这里最关键的是通过--with-mysql参数告诉mysql客户端的位置。这样才能生成mysql.so。
实验的时候,没有加这个参数,结果错误:
./configure --with-php-config=/usr/local/php524/bin/php-config
第四步:编译生成.so文件
第五步:配置php引擎加载该扩展。
补充一下:就是去php.ini文件中修改一下配置,加载mysql.so这个扩展(这个扩展文件要放到php指定的扩展目录下面去)
第六步:测试php引擎是否成功加载该扩展编写文件phpinfo.php,内容是:<?phpehco phpinfo();?>
运行后,可以看到有如下信息显示:mysqlMySQLSupport enabledActive PersistentLinks 0
Active Links 0
Client API version 5.1.55
MYSQL_MODULE_TYPE no value
MYSQL_SOCKET /tmp/mysql.sock
MYSQL_INCLUDE no value
MYSQL_LIBS no value
通过这样的方式可以确认,php引擎已经成功加载了mysql.so扩展。
第七步:已经生成的mysql.so。编写php代码测试是否能连接mysql。
8. 如何使用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;
}
}
?>
9. PHP5.5 win7系统,phpinfo()里只有mysqlnd没有mysql 求问
mysqlnd 只是mysql的驱动。需要把mydql扩展配置好才可以。查看php.ini
extension=php_mysql.dll
前面的“;”分号是否去掉,记得看一下扩展文件php_mysql.dll是不是在php的扩展目录里。
再重启一下apache或者nginx