• PHP读取配置文件连接MySQL数据库


    读取配置文件方法parse_ini_file($filepath [,$section])

    代码:

    conn.php

    <?php
    	//连接数据库
    	//$conn =new mysqli('localhost','root','','test') or die("连接失败<br/>");
    	//读取配置文件
    	$ini= parse_ini_file("test.ini");
    	$conn =new mysqli($ini["servername"],$ini["username"],$ini["password"],$ini["dbname"]) or die("连接失败<br/>");
    
    	
    	//操作数据库
    	$result=$conn->query("select * from cartoon;");
    	
    	//输出数据
    	while($row=$result->fetch_assoc()){
    		print_r($row);
    		echo "<br/>";
    	}
    	
    	//关闭数据库
    	$conn->close();
    ?>
    

    test.ini

    [mysql]
    servername="localhost"
    username="root"
    password=""
    dbname="test"
    

    输出

    1、parse_ini_file() 函数解析一个配置文件,并以数组的形式返回其中的设置。

    语法:

    parse_ini_file(file,process_sections)

    2.例子1:

    "test.ini" 的内容:

    复制代码
    [names]
    me = Robert
    you = Peter
    
    [urls]
    first = "http://www.example.com"
    second = "http://www.w3school.com.cn"
    复制代码

    PHP 代码:

    <?php
      $tmp = parse_ini_file("test.ini");
      var_dump($tmp); ?>

    输出:

    复制代码
    array(4) {
      ["me"]=>
      string(6) "Robert"
      ["you"]=>
      string(5) "Peter"
      ["first"]=>
      string(22) "http://www.example.com"
      ["second"]=>
      string(26) "http://www.w3school.com.cn"
    }
    复制代码

    例子2:

    "test.ini" 的内容:

    复制代码
    [names]
    me = Robert
    you = Peter
    
    [urls]
    first = "http://www.example.com"
    second = "http://www.w3school.com.cn"
    复制代码

    PHP 代码(process_sections 设置为 true):

    <?php
      $tmp = parse_ini_file("test.ini",true);
      var_dump($tmp); ?>

    输出:

    复制代码
    array(2) {
      ["names"]=>
      array(2) {
        ["me"]=>
        string(6) "Robert"
        ["you"]=>
        string(5) "Peter"
      }
      ["urls"]=>
      array(2) {
        ["first"]=>
        string(22) "http://www.example.com"
        ["second"]=>
        string(26) "http://www.w3school.com.cn"
      }
    }
  • 相关阅读:
    高数——微分方程的通解和特解
    高数——求极限的方法
    算法训练——删除数组零元素
    算法训练——输出米字形
    算法训练——数的统计
    算法训练——数对
    算法训练——数组查找及替换
    算法训练——数组排序去重
    算法训练——素因子去重
    算法训练——特殊的数字四十
  • 原文地址:https://www.cnblogs.com/1906859953Lucas/p/9452496.html
Copyright © 2020-2023  润新知