Database Reference
In-Depth Information
{
$in_named_group
=
1
;
# we are in a desired group
break
;
}
}
continue
;
}
if
(
!
$in_named_group
)
# we are not in a desired
continue
;
# group, skip the line
if
(
preg_match
(
"/^([^
\t
=]+)[
\t
]*=[
\t
]*(.*)/"
,
$s
,
$arg
))
$opt
[
$arg
[
1
]]
=
$arg
[
2
];
# name=value
else
if
(
preg_match
(
"/^([^
\t
]+)/"
,
$s
,
$arg
))
$opt
[
$arg
[
1
]]
=
""
;
# name only
# else line is malformed
}
return
(
$opt
);
}
Here are two examples showing how to use
read_mysql_option_file()
. The first reads
a user's option file to get the
[client]
group parameters and uses them to connect to
the server. The second reads the system-wide option file,
/etc/my.cnf
, and prints the
server startup parameters that are found there (that is, the parameters in the
[mysqld]
and
[server]
groups):
$opt
=
read_mysql_option_file
(
"/home/paul/.my.cnf"
);
$dsn
=
"mysql:dbname=cookbook"
;
if
(
isset
(
$opt
[
"host"
]))
$dsn
.=
";host="
.
$opt
[
"host"
];
$user
=
$opt
[
"user"
];
$password
=
$opt
[
"password"
];
try
{
$dbh
=
new
PDO
(
$dsn
,
$user
,
$password
);
print
(
"Connected
\n
"
);
$dbh
=
NULL
;
print
(
"Disconnected
\n
"
);
}
catch
(
PDOException
$e
)
{
print
(
"Cannot connect to server
\n
"
);
}
$opt
=
read_mysql_option_file
(
"/etc/my.cnf"
,
array
(
"mysqld"
,
"server"
));
foreach
(
$opt
as
$name
=>
$value
)
print
(
"
$name
=>
$value
\n
"
);
PHP does have a
parse_ini_file()
function that is intended for parsing
.ini
files. These
have a syntax that is similar to MySQL option files, so you might find this function of
use. However, there are some differences to watch out for. Suppose that you have a file
written like this: