php7 mysqli连接mysql的几种方式

一.过程是方法

function connect(){
     static $conn;
     if(!$conn){
         $conn = mysqli_connect(DB_HOST,DB_USER,DB_PWD) ;
     }

    if (mysqli_connect_errno($conn))
    {
        echo "连接 MySQL 失败: " . mysqli_connect_error();
    }
    mysqli_set_charset($conn,DB_CHARSET);
    mysqli_select_db($conn,DB_DBNAME) or die("指定数据库打开失败");
/* //测试查询数据库
    $sql="select category_id,category_name from category";
    //$sql = "SELECT * FROM admin";
    $result = mysqli_query($conn, $sql);
//返回所有的数据集
//var_dump(mysqli_fetch_all($result));die;
//处理返回的数据集
    $data = [];
    while($row = mysqli_fetch_assoc($result)) {
//mysqli_fetch_array
        $data[] = $row;
    }
//在页面上打印
    var_dump($data);*/
return $conn;
}
/* 调用 */
function fetchAll($sql,$result_type=MYSQLI_ASSOC){
    $conn=connect();
   $result=mysqli_query($conn,$sql);
   while(@$row=mysqli_fetch_array($result,$result_type)){
      $rows[]=$row;
   }
   return $rows;
}

 

posted @ 2019-07-15 15:17  江期玉  阅读(7194)  评论(0编辑  收藏  举报