您现在的位置是:首页 > 文章详情

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

日期:2018-08-08点击:361

读取配置文件方法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://yq.aliyun.com/articles/643648
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章