Forum und email
Ulepszone rozszerzenie MySQL

XCVIII. Ulepszone rozszerzenie MySQL

Wstęp

Rozszerzenie mysqli umożliwia dostęp do funkcjonalności dostarczanej przez MySQL w wersji 4.1 i wyższych. Więcej informacji na temat serwera bazy danych MySQL możesz znaleźć na https://www.mysql.com/

Dokumentację MySQL możesz znaleźć na https://dev.mysql.com/doc/.

Niektóre fragmenty tej dokumentacji są zaczerpnięte z podręcznika MySQL za zgodą MySQL AB.

Wymagania

Aby mieć dostęp do tych funkcji trzeba skompilować PHP ze wsparciem dla rozszrzenia mysqli.

Notatka: Rozszerzenie mysqli jest przeznaczone do pracy z wersją MySQL 4.1.3 lub wyższą. By dowiedzieć się o pozostałych wersjach zobacz dokumentację rozszerzenia MySQL.

Instalacja

By zainstalować rozszerzenie mysqli dla PHP należy użyć opcji konfiguracyjnej --with-mysqli=mysql_config_path/mysql_config, gdzie mysql_config_path wskazuje na ścieżkę dostępu do programu mysql_config, który występuje w wersjach MySQL powyżej 4.1.

Jeśli chcesz zainstalować rozszerzenie mysql razem z rozszerzeniem mysqli musisz użyć tej samej biblioteki klienckiej w celu uniknięcia konfliktów.

Konfiguracja uruchomieniowa

Na działanie tych funcji wpływają ustawienia zawarte w pliku php.ini.

Tabela 1. Opcje konfiguracyjne MySQLi

NazwaDomyślnieZmianaChangelog
mysqli.max_links"-1"PHP_INI_SYSTEMDostępna od wersji 5.0.0.
mysqli.default_port"3306"PHP_INI_ALLDostępna od wersji 5.0.0.
mysqli.default_socketNULLPHP_INI_ALLDostępna od wersji 5.0.0.
mysqli.default_hostNULLPHP_INI_ALLDostępna od wersji 5.0.0.
mysqli.default_userNULLPHP_INI_ALLDostępna od wersji 5.0.0.
mysqli.default_pwNULLPHP_INI_ALLDostępna od wersji 5.0.0.

By dowiedzieć się więcej o powyższych stałych PHP_INI_* zobacz rozdział poświęcony zmianom konfiguracji.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

mysqli.max_links integer

Maksymalna liczba połączeń MySQL na proces.

mysqli.default_port string

Domyślny port TCP używany podczas połączenia do serwera bazy danych, jeśli nie podano innego portu. Jeżeli wartość ta nie zostanie ustawiona, numer portu zostanie pobrany ze zmiennej otoczenia MYSQL_TCP_PORT,wpisu mysql-tcp w pliku /etc/services lub stałej MYSQL_PORT podanej podczas kompilacji (w takim właśnie porządku). Systemy Windows używają tylko stałej MYSQL_PORT

mysqli.default_socket string

Domyślna nazwa gniazda używanego podczas połączenia do lokalnego serwera bazy danych, jeśli inna wartość nie została podana.

mysqli.default_host string

Domyślny host używany podczas połączenia do serwera bazy danych, jeśli inna wartość nie została podana. Nie działa w trybie bezpiecznym.

mysqli.default_user string

Domyślna nazwa użytkownika używana podczas połączenia do serwera bazy danych, jeśli inna nazwa nie została podana. Nie działa w trybie bezpiecznym.

mysqli.default_pw string

Domyślne hasło używane podczas połączenia do serwera bazy danych, jeśli inne hasło nie zostało podane. Nie działa w trybie bezpiecznym.

Klasy predefiniowane

mysqli

Reprezentuje połączenie pomiędzy PHP i bazą danych MySQL.

Konstructor

  • mysqli - konstruuje nowy obiekt mysqli

Metody

  • autocommit - włącza lub wyłącza auto-potwierdzenie zmian w bazie MySQL

  • change_user - zmienia użytkownika konkretnego połączenia z bazą MySQL

  • character_set_name - wyświetla domyślne kodowanie danego połączenia z bazą MySQL

  • close - zamyka uprzednio otwarte połączenie

  • commit - wykonuje bieżącą transakcję

  • connect - otwiera nowe połączenie z bazą MySQL

  • debug - wykonuje debugging

  • dump_debug_info - zrzuca wynika debugowania

  • get_client_info - zwraca wersję klienta

  • get_host_info - zwraca rodzaj używanego połączenia

  • get_server_info - zwraca wersję serwera MySQL

  • get_server_version - zwraca wersję serwera MySQL

  • init - inicjuje obiekt mysqli

  • info - zwraca informacje na temat ostatniego zapytania

  • kill - nakzauje serwerowi zamknąć połączenie MySQL

  • multi_query - wykonuje multi-zapytanie

  • more_results - sprawdza czy istnieje więcej rezultatów ostatniego multi-zapytania

  • next_result - czyta następny rezultat z bieżącego multi-zapytania

  • options - ustawia daną opcję

  • ping - pinguje serwer bazy danych lub łączy ponownie jeśli połączenie nie istnieje

  • prepare - przygotowuje zapytanie SQL

  • query - wykonuje zapytanie

  • real_connect - próbuje nawiązać połączenie z serwerem MySQL

  • escape_string - dostosowuje znaki specjalne w łańcuchu do użycia w w instrukcji SQL biorąc pod uwagę bieżące kodowanie połączenia

  • rollback - odwołuje bieżącą transakcję

  • select_db - wybiera domyślną bazę danych

  • set_charset - ustawia domyślne kodowanie dla klienta

  • ssl_set - ustawia parametry ssl

  • stat - pobiera aktualny stan systemu

  • stmt_init- inicjuje instrukcję do użycia z mysqli_stmt_prepare

  • store_result - przekazuje zestaw wynikowy z ostatniego zapytania

  • thread_safe - zwraca wartość jeśli bezpieczeństwo wątków jest włączone lub nie

  • use_result - przesyła niebuforowany zestaw wyników ostatniego zapytania

Właściwości

  • affected_rows - zwraca liczbę używanych wierszy podczas ostatniej operacji MySQL

  • client_info - zwraca wersję klienta MySQL jako łańcuch

  • client_version - zwraca wersję klienta MySQL jako liczbę całkowitą (integer)

  • errno - zwraca kod błędu ostatnio wywołanej funkcjil

  • error - zwraca łańcuch z błędem ostatnio wywołanej funkcji

  • field_count - zwraca liczbę kolumn ostatniego zapytania

  • host_info - zwraca łańcuch zawierający typ używanego połączenia

  • info - uzyskuje informacje o ostatnio wykonanym zapytaniu

  • insert_id - zwraca automatycznie wygenerowany id używany w ostatnim zapytaniu

  • protocol_version - zwraca wersję używanego protokołu MySQL

  • server_info - zwraca łańcuch zawierający wersję serwera

  • server_version - zwraca wersję serwera jako liczbę całkowitą (integer)

  • sqlstate - zwraca łańcuch zawierający kod błędu SQLSTATE dla ostatniego błędu

  • thread_id - zwraca ID wątku dla bieżącego połączenia

  • warning_count - zwraca liczbę ostrzeżeń wygenerowanych podczas wykonywania poprzedniej instrukcji SQL

mysqli_stmt

Reprezentuje przygotowaną instrukcję.

Metody

  • bind_param - podstawia zmienne do uprzednio zdefiniowanej instrukcji

  • bind_result - przypisuje zmiennym wartość uprzednio zdefiniowanej instrukcji

  • close - kończy wykonywanie instrukcji

  • data_seek - szuka dowolnego rzędu w wyniku instrukcji

  • execute - wykonuje uprzednio zdefiniowaną instrukcję

  • fetch - pobiera wynik uprzednio zdefiniowanej instrukcji i przypisuje do konkretnych zmiennych

  • free_result - zwalnia pamięć zajętą przez wynik uprzednio zdefiniowanej instrukcji

  • prepare - przygotowywuje zapytanie SQL

  • reset - resetuje uprzednio zdefiniowaną instrukcję

  • result_metadata - pobiera zestaw wyników uprzednio zdefiniowanej instrukcji w formie danych meta

  • send_long_data - wysyła dane we fragmentach

  • store_result - łąduje do pamięci cały zestaw wyników uprzednio zdefiniowanej instrukcji

Właściwości

  • affected_rows - zwraca liczbę zmienionych wierszy podczas ostatniego wykonania instrukcji

  • errno - zwraca numer błędu ostatniego wykonania instrukcji

  • error - zwraca komunikat błędu ostatniego wykonania instrukcji

  • field_count - zwraca liczbę kolumn w zestawie wyników

  • id - zwraca identyfikator instrukcji

  • insert_id - zwraca wartość wygenerowaną dla kolumny AUTO_INCREMENT przez uprzednio zdefiniowaną instrukcję

  • num_rows - zwraca liczbę wierszy w zestawie wyników

  • param_count - zwraca ilość parametrów danej instrukcji

  • sqlstate - zwraca łańcuch zawierający kod błędu SQLSTATE ostatnio wywołanej funkcji

mysqli_result

Reprezentuje zestaw wyników uzyskany poprzez zapytanie bazy danych.

Metody

  • close - zamyka zestaw wynikowy

  • data_seek - szuka dowolnego wiersza w wyniku instrukcji

  • fetch_array - pobiera wiersz wyniku jako tablicę asocjacyjną, tablicę numeryczną lub obydwie.

  • fetch_assoc - pobiera wiersz wyniku jako tablicę asocjacyjną

  • fetch_field - podaje informację o kolumnie zestawu wynikowego

  • fetch_fields - podaje informacje o wszystkich kolumnach zestawu wynikowego

  • fetch_field_direct - podaje informację o konkretnie wskazanej kolumnie

  • fetch_object - pobiera wiersz wyniku jako obiekt

  • fetch_row - podaje rząd wyniku jako ponumerowaną tablicę

  • field_seek - ustawia wskaźnik wyniku na podane polet

  • free_result - zwalnia zajętą przez wynik pamięć

Właściwości

  • current_field - zwraca pozycję bieżącego wskaźnika pola

  • field_count - zwraca ilość pól w zestawie wynikowym

  • lengths - zwraca tablicę długości kolumn

  • num_rows - zwraca liczbę wierszy w zestawie wynikowym

  • type - zwraca MYSQLI_STORE_RESULT lub MYSQLI_USE_RESULT

Stałe predefiniowane

Tabela 2. MySQLi Constants

NameDescription
MYSQLI_READ_DEFAULT_GROUP (integer) Read options from the named group from `my.cnf' or the file specified with MYSQLI_READ_DEFAULT_FILE
MYSQLI_READ_DEFAULT_FILE (integer) Read options from the named option file instead of from my.cnf
MYSQLI_OPT_CONNECT_TIMEOUT (integer) Connect timeout in seconds
MYSQLI_OPT_LOCAL_INFILE (integer) Enables command LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND (integer) Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.
MYSQLI_CLIENT_SSL (integer) Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library
MYSQLI_CLIENT_COMPRESS (integer) Use compression protocol
MYSQLI_CLIENT_INTERACTIVE (integer) Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable.
MYSQLI_CLIENT_IGNORE_SPACE (integer) Allow spaces after function names. Makes all functions names reserved words.
MYSQLI_CLIENT_NO_SCHEMA (integer) Don't allow the db_name.tbl_name.col_name syntax.
MYSQLI_CLIENT_MULTI_QUERIES (integer)  
MYSQLI_STORE_RESULT (integer) For using buffered resultsets
MYSQLI_USE_RESULT (integer) For using unbuffered resultsets
MYSQLI_ASSOC (integer) Columns are returned into the array having the fieldname as the array index.
MYSQLI_NUM (integer) Columns are returned into the array having an enumerated index.
MYSQLI_BOTH (integer) Columns are returned into the array having both a numerical index and the fieldname as the associative index.
MYSQLI_NOT_NULL_FLAG (integer) Indicates that a field is defined as NOT NULL
MYSQLI_PRI_KEY_FLAG (integer) Field is part of a primary index
MYSQLI_UNIQUE_KEY_FLAG (integer) Field is part of a unique index.
MYSQLI_MULTIPLE_KEY_FLAG (integer) Field is part of an index.
MYSQLI_BLOB_FLAG (integer) Field is defined as BLOB
MYSQLI_UNSIGNED_FLAG (integer) Field is defined as UNSIGNED
MYSQLI_ZEROFILL_FLAG (integer) Field is defined as ZEROFILL
MYSQLI_AUTO_INCREMENT_FLAG (integer) Field is defined as AUTO_INCREMENT
MYSQLI_TIMESTAMP_FLAG (integer) Field is defined as TIMESTAMP
MYSQLI_SET_FLAG (integer) Field is defined as SET
MYSQLI_NUM_FLAG (integer) Field is defined as NUMERIC
MYSQLI_PART_KEY_FLAG (integer) Field is part of an multi-index
MYSQLI_GROUP_FLAG (integer) Field is part of GROUP BY
MYSQLI_TYPE_DECIMAL (integer) Field is defined as DECIMAL
MYSQLI_TYPE_NEWDECIMAL (integer) Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)
MYSQLI_TYPE_BIT (integer) Field is defined as BIT (MySQL 5.0.3 and up)
MYSQLI_TYPE_TINY (integer) Field is defined as TINYINT
MYSQLI_TYPE_SHORT (integer) Field is defined as INT
MYSQLI_TYPE_LONG (integer) Field is defined as INT
MYSQLI_TYPE_FLOAT (integer) Field is defined as FLOAT
MYSQLI_TYPE_DOUBLE (integer) Field is defined as DOUBLE
MYSQLI_TYPE_NULL (integer) Field is defined as DEFAULT NULL
MYSQLI_TYPE_TIMESTAMP (integer) Field is defined as TIMESTAMP
MYSQLI_TYPE_LONGLONG (integer) Field is defined as BIGINT
MYSQLI_TYPE_INT24 (integer) Field is defined as MEDIUMINT
MYSQLI_TYPE_DATE (integer) Field is defined as DATE
MYSQLI_TYPE_TIME (integer) Field is defined as TIME
MYSQLI_TYPE_DATETIME (integer) Field is defined as DATETIME
MYSQLI_TYPE_YEAR (integer) Field is defined as YEAR
MYSQLI_TYPE_NEWDATE (integer) Field is defined as DATE
MYSQLI_TYPE_ENUM (integer) Field is defined as ENUM
MYSQLI_TYPE_SET (integer) Field is defined as SET
MYSQLI_TYPE_TINY_BLOB (integer) Field is defined as TINYBLOB
MYSQLI_TYPE_MEDIUM_BLOB (integer) Field is defined as MEDIUMBLOB
MYSQLI_TYPE_LONG_BLOB (integer) Field is defined as LONGBLOB
MYSQLI_TYPE_BLOB (integer) Field is defined as BLOB
MYSQLI_TYPE_VAR_STRING (integer) Field is defined as VARCHAR
MYSQLI_TYPE_STRING (integer) Field is defined as CHAR
MYSQLI_TYPE_GEOMETRY (integer) Field is defined as GEOMETRY
MYSQLI_NEED_DATA (integer) More data available for bind variable
MYSQLI_NO_DATA (integer) No more data available for bind variable
MYSQLI_DATA_TRUNCATED (integer) Data truncation occurred. Available since PHP 5.1.0 and MySQL 5.0.5.

Przykłady

Wszystkie przykłady w dokumentacji MySQLi używają bazy danych MySQL AB. Można ją znaleźć pod adresem https://dev.mysql.com/get/Downloads/Manual/world.sql.gz/from/pick

Spis treści
mysqli_affected_rows -- Gets the number of affected rows in a previous MySQL operation
mysqli_autocommit -- Turns on or off auto-commiting database modifications
mysqli_bind_param -- Alias for mysqli_stmt_bind_param()
mysqli_bind_result -- Alias for mysqli_stmt_bind_result()
mysqli_change_user -- Changes the user of the specified database connection
mysqli_character_set_name -- Returns the default character set for the database connection
mysqli_client_encoding -- Alias of mysqli_character_set_name()
mysqli_close -- Closes a previously opened database connection
mysqli_commit -- Commits the current transaction
mysqli_connect_errno -- Returns the error code from last connect call
mysqli_connect_error -- Returns a string description of the last connect error
mysqli_connect -- Open a new connection to the MySQL server
mysqli_data_seek -- Adjusts the result pointer to an arbitary row in the result
mysqli_debug -- Performs debugging operations
mysqli_disable_reads_from_master -- Disable reads from master
mysqli_disable_rpl_parse -- Disable RPL parse
mysqli_dump_debug_info -- Dump debugging information into the log
mysqli_embedded_server_end -- 
mysqli_embedded_server_start -- 
mysqli_enable_reads_from_master -- Enable reads from master
mysqli_enable_rpl_parse -- Enable RPL parse
mysqli_errno -- Returns the error code for the most recent function call
mysqli_error -- Returns a string description of the last error
mysqli_escape_string -- Alias of mysqli_real_escape_string()
mysqli_execute -- Alias for mysqli_stmt_execute()
mysqli_fetch_array -- Fetch a result row as an associative, a numeric array, or both
mysqli_fetch_assoc -- Fetch a result row as an associative array
mysqli_fetch_field_direct -- Fetch meta-data for a single field
mysqli_fetch_field -- Returns the next field in the result set
mysqli_fetch_fields -- Returns an array of objects representing the fields in a result set
mysqli_fetch_lengths -- Returns the lengths of the columns of the current row in the result set
mysqli_fetch_object -- Returns the current row of a result set as an object
mysqli_fetch_row -- Get a result row as an enumerated array
mysqli_fetch -- Alias for mysqli_stmt_fetch()
mysqli_field_count -- Returns the number of columns for the most recent query
mysqli_field_seek -- Set result pointer to a specified field offset
mysqli_field_tell -- Get current field offset of a result pointer
mysqli_free_result -- Frees the memory associated with a result
mysqli_get_charset -- Returns a character set object
mysqli_get_client_info -- Returns the MySQL client version as a string
mysqli_get_client_version -- Get MySQL client info
mysqli_get_host_info -- Returns a string representing the type of connection used
mysqli_get_metadata -- Alias for mysqli_stmt_result_metadata()
mysqli_get_proto_info -- Returns the version of the MySQL protocol used
mysqli_get_server_info -- Returns the version of the MySQL server
mysqli_get_server_version -- Returns the version of the MySQL server as an integer
mysqli_get_warnings -- 
mysqli_info -- Retrieves information about the most recently executed query
mysqli_init -- Initializes MySQLi and returns a resource for use with mysqli_real_connect()
mysqli_insert_id -- Returns the auto generated id used in the last query
mysqli_kill -- Asks the server to kill a MySQL thread
mysqli_master_query -- Enforce execution of a query on the master in a master/slave setup
mysqli_more_results -- Check if there are any more query results from a multi query
mysqli_multi_query -- Performs a query on the database
mysqli_next_result -- Prepare next result from multi_query
mysqli_num_fields -- Get the number of fields in a result
mysqli_num_rows -- Gets the number of rows in a result
mysqli_options -- Set options
mysqli_param_count -- Alias for mysqli_stmt_param_count()
mysqli_ping -- Pings a server connection, or tries to reconnect if the connection has gone down
mysqli_prepare -- Prepare a SQL statement for execution
mysqli_query -- Performs a query on the database
mysqli_real_connect -- Opens a connection to a mysql server
mysqli_real_escape_string -- Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection
mysqli_real_query -- Execute an SQL query
mysqli_report -- Enables or disables internal report functions
mysqli_rollback -- Rolls back current transaction
mysqli_rpl_parse_enabled -- Check if RPL parse is enabled
mysqli_rpl_probe -- RPL probe
mysqli_rpl_query_type -- Returns RPL query type
mysqli_select_db -- Selects the default database for database queries
mysqli_send_long_data -- Alias for mysqli_stmt_send_long_data()
mysqli_send_query -- Send the query and return
mysqli_server_end -- Shut down the embedded server
mysqli_server_init -- Initialize embedded server
mysqli_set_charset -- Sets the default client character set
mysqli_set_local_infile_default -- Unsets user defined handler for load local infile command
mysqli_set_local_infile_handler -- Set callback functions for LOAD DATA LOCAL INFILE command
mysqli_set_opt -- Alias of mysqli_options()
mysqli_slave_query -- Force execution of a query on a slave in a master/slave setup
mysqli_sqlstate -- Returns the SQLSTATE error from previous MySQL operation
mysqli_ssl_set -- Used for establishing secure connections using SSL
mysqli_stat -- Gets the current system status
mysqli_stmt_affected_rows -- Returns the total number of rows changed, deleted, or inserted by the last executed statement
mysqli_stmt_attr_get -- 
mysqli_stmt_attr_set -- 
mysqli_stmt_bind_param -- Binds variables to a prepared statement as parameters
mysqli_stmt_bind_result -- Binds variables to a prepared statement for result storage
mysqli_stmt_close -- Closes a prepared statement
mysqli_stmt_data_seek -- Seeks to an arbitray row in statement result set
mysqli_stmt_errno -- Returns the error code for the most recent statement call
mysqli_stmt_error -- Returns a string description for last statement error
mysqli_stmt_execute -- Executes a prepared Query
mysqli_stmt_fetch -- Fetch results from a prepared statement into the bound variables
mysqli_stmt_field_count -- Returns the number of field in the given statement
mysqli_stmt_free_result -- Frees stored result memory for the given statement handle
mysqli_stmt_get_warnings -- 
mysqli_stmt_init -- Initializes a statement and returns an object for use with mysqli_stmt_prepare
mysqli_stmt_insert_id -- Get the ID generated from the previous INSERT operation
mysqli_stmt_num_rows -- Return the number of rows in statements result set
mysqli_stmt_param_count -- Returns the number of parameter for the given statement
mysqli_stmt_prepare -- Prepare a SQL statement for execution
mysqli_stmt_reset -- Resets a prepared statement
mysqli_stmt_result_metadata -- Returns result set metadata from a prepared statement
mysqli_stmt_send_long_data -- Send data in blocks
mysqli_stmt_sqlstate -- Returns SQLSTATE error from previous statement operation
mysqli_stmt_store_result -- Transfers a result set from a prepared statement
mysqli_store_result -- Transfers a result set from the last query
mysqli_thread_id -- Returns the thread ID for the current connection
mysqli_thread_safe -- Returns whether thread safety is given or not
mysqli_use_result -- Initiate a result set retrieval
mysqli_warning_count -- Returns the number of warnings from the last query for the given link