|
|
LXXI. 改良版MySQL拡張サポート(mysqli)
mysqli拡張サポートによってMySQL4.1以上で提供される機能を利用することが
できるようになります。MySQLデータベースサーバに関する詳細は
をご覧ください。
MySQLに関するドキュメントは
にあります。
このドキュメントの一部は、MySQL ABの許可を得てMySQLマニュアルから引用
したものです。
これらの関数を有効にするには、mysqli拡張サポートを
有効にしてPHPをコンパイルする必要があります。
注意:
mysqli拡張サポートはMySQL 4.1.2以上で動作するよう設計されています。
それ以前のバージョンについてはMySQL
拡張サポートのドキュメントをご覧ください。
PHPにmysqli拡張サポートを追加するには、
--with-mysqli=mysql_config_path
オプションを指定してPHPをコンパイルする必要があります。
mysql_config_pathにはMySQL4.1以上に付属する
mysql_configプログラムが存在するパスを
指定してください。同時に、--without-mysqlオプションを
使って標準のMySQL拡張
(これはデフォルトでコンパイルされます)をはずしてください。
mysqli拡張サポートと標準のmysql拡張を共存させる形でインストールしたい
場合には、PHPにバンドルされているlibmysqlライブラリは使用できません。
代わりにMySQL4.1未満でインストールされるクライアントライブラリを
使用してください。これにより何ら衝突させることなく
MySQLでインストールされるクライアントライブラリをPHPが強制的に
使用するようにできます。
これらの関数の動作は、php.iniの設定により変化します。
表 1. MySQLi 設定オプション 名前 | デフォルト | 変更の可否 |
---|
mysqli.max_links | "-1" | PHP_INI_SYSTEM | mysqli.default_port | NULL | PHP_INI_ALL | mysqli.default_socket | NULL | PHP_INI_ALL | mysqli.default_host | NULL | PHP_INI_ALL | mysqli.default_user | NULL | PHP_INI_ALL | mysqli.default_pw | NULL | PHP_INI_ALL |
PHP_INI_* 定数の詳細と定義については、
設定の変更
を参照して下さい。
以下に設定ディレクティブに関す
る簡単な説明を示します。
- mysqli.max_links
integer
持続的接続を含むプロセス毎の
MySQL接続の最大数。
- mysqli.default_port
string
他のポートが指定されない場合、データベースサーバ接続時に
使用されるデフォルトのTCPポート番号。デフォルトが指定されない
場合、ポートは、環境変数MYSQL_TCP_PORT、
/etc/servicesの
mysql-tcpエントリ、コンパイル時の
MYSQL_PORT定数の順番で取得されます。
Win32では、MYSQL_PORT定数のみが使用されます。
- mysqli.default_socket
string
他にソケット名が指定されない場合、ローカルな
データベースサーバに接続する時のデフォルトのソケット名。
- mysqli.default_host
string
他のサーバ名が指定されない場合に、データベースサーバへの接続時に
使用されるデフォルトのサーバ名。
safe modeでは適用されません。
- mysqli.default_user
string
他のユーザ名が指定されない場合に、データベースサーバへの接続時に
使用されるデフォルトのユーザ名。
safe modeでは適用されません。
- mysqli.default_password
string
他のパスワードが指定されない場合に、データベースサーバへの接続時に
使用されるデフォルトのパスワード。
safe modeでは適用されません。
PHPとMySQLデータベースの間の接続を表します。
affected_rows - gets the number of affected rows in a previous MySQL operation errno - returns the error code for the most recent function call error - returns the error string for the most recent function call field_count - returns the number of columns for the most recent query host_info - returns a string representing the type of connection used info - retrieves information about the most recently executed query insert-id - returns the auto generated id used in the last query protocol_version - returns the version of the MySQL protocol used sqlstate - returns a string containing the SQLSTATE error code for the last error thread_id - returns the thread ID for the current connection warning-count - returns the number of warnings generated during execution of the previous SQL statement
パースされた命令を表します。
bind_param - Binds variables to a prepared statement bind_result - Binds variables to a prepared statement for result storage close - Closes a prepared statement data-seek - Seeks to an arbitrary row in a statement result set execute - Executes a prepared statement fetch - Fetches result from a prepared statement into bound variables get_metadata - Retrieves a resultset from a prepared statement for metadata information send_long_data - Sends data in chunks store_result - Buffers complete resultset from a prepared statement
affected_rows - Returns affected rows from last statement execution field_count - Returns number of fields for a given prepared statement errno - Returns errorcode for last statement function errno - Returns errormessage for last statement function param_count - Returns number of parameter for a given prepare statement sqlstate - returns a string containing the SQLSTATE error code for the last statement function
データベースへのクエリにより得られた結果セットを表します。
close - closes resultset data_seek - moves internal result pointer fetch_field - gets column information from a resultset fetch_fields - gets information for all columns from a resulset fetch_field_direct - gets column information for specified column fetch_array - fetches a result row as an associative array, a numeric array, or both. fetch_assoc - fetches a result row as an associative array fetch_object - fetches a result row as an object fetch_row - gets a result row as an enumerated array close - frees result memory field_seek - set result pointer to a specified field offset
add a note
User Contributed Notes
改良版MySQL拡張サポート(mysqli)
Andrei Nazarenko
22-Feb-2005 07:21
If you are having trouble compiling PHP5 with MySQLi support on Linux and getting a message:
"configure: error: wrong mysql library version or lib not found"
and the config.log shows an error about -lnss_files being not found, here is the solution:
edit your mysql_config file and *REMOVE* all "-lnss_files" AND "-lnss_dns" entries from it.
After that PHP should not complain anymore.
neil
10-Feb-2005 10:15
I have spent far too much time finding this answer:
Since PHP5 many many people are having installation problems. I found many apps were broken when I upgraded to version 5. I tried to install mysql and mysqli and had problems.
Here's the solution:
After doing:
./configure --with-mysql=/path/to/mysql_config --with-mysqli=/path/to/mysql_config
do this:
"
if you want to use both the old mysql and the new mysqli interface, load the Makefile into your editor and search for the line beginning with EXTRA_LIBS; it includes -lmysqlclient twice; remove the second instance
"
then you can:
make
make install
......
Please note: the mysql-dev must be installed or you won't have a mysql_config anywhere. I installed the mysql-dev rpm
Further note: the information about the Makefile's duplicate instances of "-libmysqlclient" came from Michael Kofler. Thanks should be directed to him. He gives more details at the following link:
K dot Londenberg at librics dot de
10-Feb-2005 05:35
Second part of the mysqli wrapper code since it didn't all get into one note
------ exception.php -------------
<?php
class FatalException extends Exception {};
class ErrorException extends Exception {};
class WarningException extends Exception {};
function exceptionErrorHandler($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_USER_ERROR:
throw new FatalException($errstr, $errno);
break;
case E_USER_WARNING:
case E_WARNING:
throw new WarningException($errstr, $errno);
break;
case E_USER_NOTICE:
break;
default:
echo " - Unknown error - <b>$errstr</b>($errno) <br>";
break;
}
}
$old_error_handler = null;
function install_exception_errorhandler() {
global $old_error_handler;
$old_error_handler = set_error_handler(exceptionErrorHandler);
}
function uninstall_exception_errorhandler() {
global $old_error_handler;
set_error_handler($old_error_handler);
$old_error_handler = null;
}
function exception_dump(&$e) {
$res = "";
$res .= "<br><h2>".get_class($e)."</h2>\n";
$res .= "<h3>{$e->getMessage()} ({$e->getCode()})</h3>\n\n";
$res .= "file: {$e->getFile()}<br/>\n";
$res .= "line: {$e->getLine()}<br/>\n";
$res .= "<PRE>";
$res .= $e->getTraceAsString();
$res .= "</PRE><br>";
return $res;
}
?>
-------------------------------------------
Example-Code:
------ example.php ------------------------
<?php
require_once('safe_mysqli.php');
try {
$mysql = new safe_mysqli('locashost', 'user', 'pass', 'test');
$stmt = $mysql->prepare("SELECT city, city_accented, population, latitude, longitude from world_cities where city like ? order by population desc limit 5");
$stmt->bind_param('s', $a);
$stmt->bind_result($city, $city_accented, $population, $latitude, $longitude);
foreach ($anfangsbuchstaben as $a) {
$stmt->execute();
while ($stmt->fetch()) {
echo "<b>$city_accented</b>: pop $population - Lat. $latitude Long. $longitude<br>";
}
$stmt->free_result();
}
} catch (SQLException $e) {
die("SQL Error : ".$e->getSQLError()." in <hr><PRE>".$e->getSQL()."</PRE><hr>");
} catch (DBException $e) {
die("Database Error: ". $e->GetMessage());
} catch (Exception $e) {
die(exception_dump($e));
}
?>
-----------------------------------------
Hope this helps ...
K dot Londenberg at librics dot de
10-Feb-2005 05:34
I wrote a wrapper class for mysqli which adds exception handling to the code. It's based on the second tutorial at zend.com
It partially relies on another small library which enables translation from php-warnings to exceptions, so I'm going to include this code as well.
-------safe_mysqli.php------------
<?php
require_once('exceptions.php');
install_exception_errorhandler(); class DBException extends Exception {}; class DBConnectException extends DBException {} class SQLException extends DBException {
private $sql;
private $sqlerrmsg;
function __construct($msg, $code, $sql) {
$this->sqlerrmsg = $msg;
if (defined('SQL_DEBUG')) {
$msg .= " in '$sql'";
}
parent::__construct($msg, $code);
$this->sql = $sql;
}
function getSQL() {
return $this->sql;
}
function getSQLError() {
return $this->sqlerrmsg;
}
}
function add_single_quotes($arg)
{
return "'" . addcslashes($arg, "'\\") . "'";
}
class safe_mysqli extends mysqli {
function __construct() {
$args = func_get_args();
try {
eval("parent::__construct(" . join(',', array_map('add_single_quotes', $args)) . ");");
} catch (WarningException $we) {
if(mysqli_connect_error()){
throw new DBConnectException(mysqli_connect_error(), mysqli_connect_errno());
}
}
}
function query($query) {
$result = parent::query($query);
if(mysqli_error($this)){
throw new SQLException(mysqli_error($this), mysqli_errno($this), $query);
}
return $result;
}
function prepare($query) {
$result = parent::prepare($query);
if(mysqli_error($this)){
throw new SQLException(mysqli_error($this), mysqli_errno($this), $query);
}
return $result;
}
}
?>
php at arwin dot net
02-Feb-2005 11:32
For those having trouble compiling with both --with-mysql AND --with-mysqli, I found a solution at this URL:
rjanson at msn dot com writes:
OK, finally an answer!
I checked Makefile and found the following line:
EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lpng -lz -lz -lresolv -lm
-ldl -lnsl -lxml2 -
lz -lm -lxml2 -lz -lm -lmysqlclient -lcrypt -lnsl -lm -lz -lnss_files
-lnss_dns -lresolv -lnss_files
-lnss_dns -lresolv -lxml2 -lz -lm -lcrypt -lxml2 -lz -lm -lcrypt
By removing one of the -lmysqlclient entries on this line I was able to
successfully make and make install with both mysql and mysqli. As
confirmed by phpInfo().
I'm not sure why the other libs have multiple entries and don't cause
make to crash.
roberto at spadim dot com dot br
07-Dec-2004 03:34
Mysqli is slower them mysql extension if you not use pre compiled statments!
Yair Lapin
10-Nov-2004 03:28
I successed to install php support for a mysql 4.1.7 database after several attempts because the instructions are not clear.
I have a server with linux SuSe 9 enterprise with apache 1.3.31. I installed mysql from rpm files, i installed php 4.3.9 as dynamic library. this version database needs its own client library else the mysql functions in php will not work.
configuration must be as following:
./configure --with-msqli=/usr/bin/mysql_config --with-mysql=/usr --with-apxs=/usr/local/apache/bin/apxs
Must be installed in your machine the correct mysql librery:
MySQL-devel-4.1.7-0
MySQL-shared-4.1.7-0
David Woakes
29-Sep-2004 05:41
I installed MySQL 4.1.4 in Fedora Core 2 using rpms from MySQL:
MySQL-client-4.1.4-0
MySQL-server-4.1.4-0
MySQL-devel-4.1.4-0
MySQL-shared-4.1.4-0
I configured with --with-mysqli=/usr/bin/mysql_config and --with-mysql=/usr and was getting duplicate symbol definitions at the end of make.
I worked out that the linking stage was including the shared libs (from MySQL-shared) and the static libs (from MySQL-devel). Uninstalling the devel package doesn't help because you need the include files. The solution I came up with was to delete the static lib files. Not perfect, but it got there.
nathansquires at pacbell dot net
13-Sep-2004 05:44
If you want to build php with both the Mysql and mysqli extensions, make sure your mysql distribution comes with shared libraries or build mysql yourself with shared libraries. With only static mysql libraries the compile process will fail.
severin dot kacianka at aon dot at
12-Aug-2004 10:55
I tryed Marco Kaiser's way of getting both mysql_* and mysqli_*, but it failed for me. However I could get it working this way:
First of all I installed the MySQL 4.1.3 binary disribution acourding to the manual. Then I simply passed these ./configure arguments:
--with-mysql=/path/to/mysql4.1.3
--with-mysqli=/path/to/mysql4.1.3/bin/mysql_config
This enabled both, the mysql_* and mysqli_* functions.
Severin Kacianka
ajp at aripollak dot com
19-Jul-2004 11:50
From README.PHP4-TO-PHP5-THIN-CHANGES:
Be careful when porting from ext/mysql to ext/mysqli. The following
functions return NULL when no more data is available in the result set
(ext/mysql's functions return FALSE).
- mysqli_fetch_row()
- mysqli_fetch_array()
- mysqli_fetch_assoc()
philip
17-Jun-2004 10:51
A couple tutorials on the subject of mysqli:
*
*
phoeniks[at]nm[dot]ru
08-Apr-2004 10:21
Here is a little sample to do fast hierarchical queries using new prepared statements
<?php
function tree_rise($root, &$stack, $top = 0) {
$mysqli = mysqli_connect('localhost', 'root');
$top = (int)$top;
$stmt = mysqli_prepare($mysqli, "SELECT id, pid, title FROM news.strg WHERE id = ? LIMIT 1");
mysqli_stmt_bind_param($stmt, "i", $root);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_bind_result($stmt, $id, $root, $title);
while (mysqli_fetch($stmt)) {
$stack[$id] = $title;
if ($root != $top && !is_null($root)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
}
}
return count($stack);
}
?>
Marco Kaiser
03-Nov-2003 07:51
I installed
mysql 4.0.xx and mysql 4.1.xx (mysql & mysqli) with
--with-mysql=/path/to/mysql4/
--with-mysql=/path/to/mysql4.1/bin/mysql_config
keep in mind don't use --with-embedded-mysqli !!
Its doesn't work if you just give mysqli the path where mysql_config is.
| |