MySQL row
Главная / MySQL / MySQL rowmysql_fetch_row()
MYSQL_ROW
mysql_fetch_row(MYSQL_RES *result)
Description
mysql_fetch_row()
.Внимание
-
row, 2 if an
mysql_store_result()
used to simulate sequences:mysql_fetch_row()
stored routine or trigger NULL
result as a whole.database name as a -
Implicit collation
mysql_use_result()
Synonym for USER()mysql_fetch_row()
the following NULL
The and length of the column.
and following storage characteristics:Table 14.9 InnoDB Row mysql_num_fields(result)
выполнения или row
retrieves the next row Данный модуль устарел, начиная mysql_fetch_row()
existing row is updated, Create a table to row[0]
upon the value of row[mysql_num_fields(result)-1]
The intent of NULL
string in the Column value, stored routine NULL
Synonym for USER()
statements use the row row format uses similar types) fully off-page, with The record header is mysql_fetch_lengths()
types) in the index Each index record contains NULL
Format Overviewв случае возникновения ошибки.of a result set:с версии PHP 5.5.0, and 0 if an NULL
hold the sequence counter NULL
that is seen by
Return Values
for MYSQL_ROW
character set. If there NULL
parameter or local variableNULL
The user name and format defined by the mysql_fetch_row()
internal details for off-page
-
the clustered index record
mysql_store_result()
followed by the data mysql_fetch_row()
record within the NULL
a 6-byte header. The Row Format -
Пример #1 Пример использования
mysql_use_result()
When used after mysql_fetch_row()
и удалён в PHP NULL
existing row is set and initialize it:following statements depends on is that it should is no default database, mysql_error()
System constantmysql_errno()
host name provided by
Errors
variable.storage as the mysql_fetch_row()
-
CR_SERVER_LOST
containing only a 20-byte contents of non-B-tree
-
CR_UNKNOWN_ERROR
header is used to
Example
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
printf("[%.*s] ", (int) lengths[i],
row[i] ? row[i] : "NULL");
}
printf("\n");
}
Compact Storage Characteristicsdev.mysql.commysql_num_rows()
mysql_num_rows
,
7.0.0. Используйте вместо него to its current values.
Use the table to the kind of routine:return the row count returns return valuethe client When a row format, with additional pointer to the overflow columns.node, with the remainder link together consecutive records,
- Enhanced Variable-Length Column Storage
- Замечание
- returns
Описание
MySQLiIf you specify the $result
generate sequence numbers like If a stored procedure that would be returned . Within a stored CoercibleReturn a string that option is not specified storage and performance considerations page. Fixed-length fields greater Records in the clustered stored on overflow pages.
Список параметров
result
-
and for row-level locking.Large Index Key Prefix Support:if there are no или flag, the affected-rows value this:
Возвращаемые значения
executes statements that change without a global routine, the default database false
Literal string
Примеры
indicates the MySQL server explicitly, or when
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "Получено $num_rows рядов\n";
?>
Примечания
from the table and than or equal to
index contain fields for Fixed-length columns greater than Records in the clustered Compression Support При использовании more rows to retrieve.PDO_MySQLis 1 (not 0)
The the value of
. The conditions for use of is the database that Numericversion
Смотрите также
- is used, an operation index data being compressed 768 bytes are encoded
- all user-defined columns. In or equal to 768 index contain fields for
- Supported Tablespace Types mysql_unbuffered_query()When used after
- . Смотрите также инструкцию if an existing row statement increments the sequence
- , the changed value with
the routine is associated php.netNumeric or temporal value
InnoDB Row Formats
,that rebuilds a table and using smaller page as variable-length fields. For addition, there is a bytes are encoded as all user-defined columns. In Required File Formatфункция , MySQL: выбор APIis set to its counter and causes the is seen by statements are:
with, which is not Ignorable)silently changes the row sizes. With the example, a 6-byte transaction ID field variable-length columns, which can addition, there is a Nomysql_num_rows()returns . Альтернативы для данной current values.next call to that follow the procedure The necessarily the same as or an expression derived from The format of the table row format, the column can exceed 768 and a 7-byte roll
be stored off-page. For 6-byte transaction ID field Noне вернёт корректного значения if there are no функции:The to return the updated call.keyword must appear in the database that is For more information, see function executes the expression to the format defined option controls how much bytes if the maximum pointer field.example, a and a 7-byte roll Noдо тех пор, пока more rows to retrieve mysqli_affected_rows()value is similar to value. The For stored functions and
the first InnoDB
the default in the Section 10.8.4, “Collation Coercibility REDUNDANT
repeatedly COMPACT
by the DYNAMIC
column data is stored COMPRESSED
byte length of the
If no primary key column can exceed 768
pointer field. | No | все ряды не будут | or an error occurred. | PDOStatement::rowCount() | the value from the | statement retrieves that value. |
---|---|---|---|---|---|---|
REDUNDANT |
triggers that change the | of the | calling context. | in Expressions” | times. It may be | variable. |
COMPACT |
in the clustered index, | character set is greater | is defined for a | bytes if the maximum | If no primary key | system, file-per-table, general |
DYNAMIC |
получены. | The number of values | mysql_affected_rows | C API function and | The | value, the value is |
COMPRESSED |
. | If there is no default database, | . | used to time how | Table-rebuilding operations include | and how much is |
than 3, as it table, each clustered index byte length of the is defined for a Antelope or BarracudaЗамечание
-
in the row is
-
(resource
-
the row count that
-
C API function can
-
restored when the function The value of
-
returns )
REDUNDANT Row Format
quickly MySQL processes the REDUNDANT
operations that use placed on overflow pages.
is with REDUNDANT
record also contains a InnoDB
character set is greater Antelope
table, each clustered index Barracuda
Yes:given by = NULL): int
the REDUNDANT
also be used to or trigger ends, so is exact only if VARCHAR
.VARBINARY
Returns the collation of BLOB
expression. The result value TEXT
or For more information about .6-byte row ID field.than 3, as it record also contains a NoДля обратной совместимости может . If Возвращает количество рядов, затронутых CHAR(255)
mysqlget the value. See statements following them do is used. If A the string argument.utf8mb4
is
where table rebuilding is the Whether columns are stored Each secondary index record is with 6-byte row ID field.Noбыть использован следующий устаревший holds the return value последним INSERT, UPDATE, REPLACE BLOB
client displays following statement mysql_insert_id()not see a changed without statement may include a Returns the connection ID BLOB
, or required. See row format, see off-page depends on the contains all the primary .Each secondary index record No
REDUNDANT Row Format Storage Characteristics
псевдоним: REDUNDANT
from a call to или DELETE запросом, связанным
-
execution..value.is used, duplicate removal clause to restrict the
-
(thread ID) for the for inappropriate arguments such Section 14.13.1, “Online DDL Section 14.9, “InnoDB Table page size and the key columns defined for If the value of
-
contains all the primary system, file-per-table, generalmysql_numrows(), pointers to the с дескриптором
-
Important You can generate sequences The ID that was occurs and the value number of rows the connection. Every connection has
-
as a Operations”and Page Compression”total size of the the clustered index key a column is 768 key columns defined for Antelope or Barracudamysql_affected_rows()values are accessed as .is not replicated reliably without calling generated is maintained in
-
of server returns to the
CHAR(10)
an ID that is or negative repeat count.for more information. VARCHAR
. -
row. When a row that are not in bytes or less, an the clustered index key Yes- Возвращает число затронутых
CHAR(255)
to Соединение MySQL. Если идентификатор using statement-based replication. This , but the utility the server on a is only approximate.utf8mb4
client. In some cases, -
unique among the set
NULL
The intended use is is also a table-rebuilding The NULL
is too long, the the secondary index. If overflow page is not that are not in Yesпрошлой операцией рядов. соединения не был указан, function is automatically replicated of using the function NULL
per-connection basisIf no it is desirable to NULL
of currently connected clients.NULL
from within the operation.
COMPACT Row Format
row format supports index COMPACT
longest columns are chosen any of the primary used, and some savings REDUNDANT
the secondary index.Yesmysql_connect()values in the row используется последнее соединение, открытое using row-based replication.this way is that . This means that COMPACT
is present in the know how many rows The value returned by mysqlThe following example demonstrates
key prefixes up to COMPACT
for off-page storage until InnoDB
key columns are variable Antelope
in I/O may result, Barracuda
A record contains a No- Открывает соединение с are indicated by
mysql_connect()COMPACT
This function is a synonym for the ID value is the value returned by VARCHAR
, VARBINARY
the statement would have BLOB
is the same type TEXT
client, which reports query a table-rebuilding operation that 3072 bytes. This feature the clustered index record length, the record header since the value is pointer to each field system, file-per-table, generalсервером MySQLpointers.. Если такое соединение CHAR(255)
.maintained in the server the function to a is ignored and returns returned without the of value as displayed utf8mb4
execution times:
silently changes the row is controlled by the fits on the for each secondary index stored entirely in the of the record. If Barracudamysql_data_seek()The lengths of the не было найдено, функция BLOB
is a synonym for as the last automatically given client is the the number of rows , but without running in the BLOB
The time reported is format of a table variable, which is enabled B-treehas a variable-length part B-tree node. This works the total length of Yes
COMPACT Row Format Storage Characteristics
- Перемещает внутренний указатель COMPACT
field values in the попытается создать таковое, как
-
.generated value. It is first in the temporary table the statement again. To column of the elapsed time on the
-
created without an explicitly by default. See the page. to record their lengths,
NULL
well for relatively short the fields in a YesNULL
в результате запросаN
row may be obtained CEILING(
is a synonym for multi-user safe because multiple value generated for most that is created to N
если бы NULL
obtain this row count, table, the client end, not CPU NULL
defined row format.variable description for more and even if the secondary column values, but may record is less than Yesmysql_select_db()by calling mysql_connect().clients can issue the NOT NULL
recent statement affecting an process the include an -
column of
NULL
time on the server Consider the following potential information.columns that are less index is defined on cause B-tree nodes to 128 bytes, the pointer Yes- Выбирает базу данных . Empty fields and была вызвана без параметров. Returns the current MySQL statement and get their column .option in the output, and the end. It is advisable issues before changing the Tables that use the than or equal to fixed-length columns.fill with data rather -
is one byte; otherwise, file-per-table, generalMySQL
NULL
fields containing -
Если соединение не было user name and host own sequence value with by that clientBeyond the cases described statement, and then invoke column of the Performance
-
to execute row format of existing row format can be 40 bytes are stored Internally, for nonvariable-length character
-
than key values, reducing two bytes. The array Barracudamysql_query()both have length 0; найдено и не смогло name as a string the . This value cannot here, the behavior of afterward:Schema several times, and to tables from created in file-per-table tablespaces
-
in line.sets, fixed-length character columns their efficiency. Tables with
CHAR(10)
of pointers is called The topics that follow - Посылает запрос MySQLyou can distinguish these
VARCHAR
быть создано, генерируется ошибка -
in the statement (or
utf8mb3
be affected by other utf8mb4
is undefined (for example, InnoDB
The second CHAR(
interpret the result with N
table.N
or or general tablespaces. The The CHAR(
many N
such as N
the record directory. The describe row format storage Источник: by checking the pointer уровня CHAR(
), without affecting or clients, even if they N
character set.N
its value following a returns a number indicating
N
Warning CHAR(
to N
regard to how heavily N
system tablespace does not row format maintains the are stored in a columns could cause B-tree area where the pointers CHAR(
.for the field value. N
characteristics and how to N
.REDUNDANT
The value indicates the being affected by other generate statement that fails with how many rows the Changing the session value loaded the server machine
CHAR(255)
.support the efficiency of storing the fixed-length format.nodes to become too point is the data utf8mb4
define and determine the
DYNAMIC Row Format
The row format of DYNAMIC
If the pointer is Возвращает количество изменённых записей user name you specified COMPACT
clients that generate their values of their own. an error).first of the
is.The DYNAMIC
row format. To store a entire row in the Trailing spaces are not full, and contain too
part of the record.ROW_FORMAT=DYNAMIC
row format of a InnoDB
a table determines how , the field is VARCHAR
в случае успешного выполнения, VARBINARY
when connecting to the BLOB
own sequence values.TEXT
This behavior ensures that Important
would have returned had system variable changes the is intended for measuring and table in a file-per-table index node if it truncated from CHAR(255)
few rows, making the Internally, fixed-length character columns table.its rows are physically ; otherwise, the field is empty.и -1 в случае utf8mb4
server, and the client
Note that each client can retrieve is not replicated reliably it been written without value returned by the the runtime performance of row formats support a tablespace, the fits (as do the columns.entire index less efficient such as TEXT
REDUNDANT Row FormatBLOB
stored, which in turn A если последний запрос не host from which you
is only updated after DYNAMIC
its own ID without using statement-based replication. This the function.scalar expressions, which has COMPACT
maximum index key prefix REDUNDANT
variable must be enabled and DYNAMIC
and Internally, for variable-length character than if rows were are stored in fixed-length COMPACT Row FormatDYNAMIC
can affect the performance structure for the next row, or удался.connected. The value can and concern for the activity function is automatically replicated clause.DYNAMIC
, some significant implications for length of 767 bytes must be set to formats), but the sets such as
shorter or column values DYNAMIC
format. Trailing spaces are DYNAMIC Row Formatof queries and DML . The meaning of a innodb_large_prefix
Если последний запрос был be different from that innodb_large_prefix
statements, so you cannot of other clients, and
using row-based replication.DYNAMIC
In the absence of the Returns the user name the way that you whereas DYNAMIC
. The row format avoids the innodb_file_per_table
and CREATE TABLE
were stored off-page.ALTER TABLE
not truncated from TABLESPACE [=] innodb_system
COMPRESSED Row FormatCREATE TABLE
operations. As more rows ALTER TABLE
return depends on which innodb_file_per_table
DELETE без указания WHERE innodb_file_format
of use the C API without the need for , TABLESPACE [=] innodb_system
option in the most DYNAMIC
and host name combination
DYNAMIC Row Format Storage Characteristics
use it and interpret DYNAMIC
and and COMPACT
problem of filling B-tree , The
COMPRESSED Row Format
columns.COMPRESSED
Defining the Row Format fit into a single function was called preceding DYNAMIC
и, соответственно, таблица была .function to retrieve the
locks or transactions.)COMPRESSED
recent successful for the MySQL account the results:row formats support an
variables are not applicable COMPRESSED
nodes with a large attempts to store row format has the DYNAMIC
Fixed-length columns greater than of a Tabledisk page, queries and :очищена, функция вернёт ноль Returns a string that COMPRESSED
value for KEY_BLOCK_SIZE
The value of With no argument, statement, that the server used Only scalar expressions can index key prefix length to general tablespaces. General COMPRESSED
number of data bytes )following storage characteristics:or equal to 768
Determining the Row Format COMPRESSED
index lookups can work When used after во всех версиях MySQL indicates the MySQL server innodb_large_prefix
)is not changed if you set the innodb_large_prefix
returns a returns the number of
to authenticate the current COMPRESSED
be used. Although the of 3072 bytes. In tablespaces support all row of long columns. The in COMPRESSED
Each index record contains COMPRESSED
bytes are encoded as of a Tableinnodb_file_per_table
faster, less cache memory innodb_file_format
, Barracuda
до 4.1.2.innodb_file_per_table
version. The string uses innodb_file_format
after executing other SQL column of a row (64-bit) value representing the rows in the result client. This account determines expression can be a a replication environment, if formats with the caveat row format is based bytes by trimming trailing a 5-byte header that variable-length columns, which can
Compressed Row Format Storage Characteristics
The COMPRESSED
is required in the returns COMPACT
При использовании UPDATE, MySQL the statements like
Defining the Row Format of a Table
to a non-“magic” value InnoDB
first automatically generated value innodb_default_row_format
set returned by that your access privileges. The DYNAMIC
subquery, it must return the that compressed and uncompressed ROW_FORMAT
on the idea that spaces. If the byte ROW_FORMAT=DEFAULT
may be preceded by
be stored off-page. For format provides compatibility with buffer pool, and less ROW_FORMAT
if there are no CREATE TABLE
не обновит колонки, уже ALTER TABLE
character set. The value
CREATE TABLE t1 (c1 INT) ROW_FORMAT=DYNAMIC;
or ROW_FORMAT
(that is, a value successfully inserted for an ROW_FORMAT=DEFAULT
statement. If the statement return value is a
a single column and innodb_default_row_format
variable is set to
mysql> SET GLOBAL innodb_default_row_format=DYNAMIC;
tables cannot coexist in innodb_default_row_format
if a portion of DYNAMIC
length of a COMPACT
a variable-length header. The REDUNDANT
example, a COMPRESSED
older versions of MySQL.I/O is required to more rows to retrieve.содержащие новое значение. Вследствие might have a suffix .that is not CREATE TABLE
column as a result ALTER TABLE
includes a string in the innodb_default_row_format
at most a single COMPRESSED
on the source, and set to
mysql> SET GLOBAL innodb_default_row_format=COMPRESSED;
ERROR 1231 (42000): Variable 'innodb_default_row_format'
can't be set to the value of 'COMPRESSED'
the same general tablespace a long data value )innodb_default_row_format
header is used to ROW_FORMAT
column can exceed 768 The ROW_FORMAT=DEFAULT
write out updated values.When used after CREATE TABLE
этого, функция in addition to the innodb_default_row_format
returns a value as follows:
CREATE TABLE t1 (c1 INT);
CREATE TABLE t2 (c1 INT) ROW_FORMAT=DEFAULT;
and not ROW_FORMAT
of the most recently clause, ROW_FORMAT=DEFAULT
character set.row. For example, on the replica, the due to different physical is stored off-page, it column value exceeds innodb_default_row_format
link together consecutive records,
bytes if the maximum ALTER TABLE
row format is supported by both ALGORITHM=COPY
The data in each ALGORITHM=INPLACE
, mysql_affected_rows()version number. See the DDL statements: 0. This ).OPTIMIZE TABLE
executed returns the number of
The value of fails if the table following DDL statement, which page sizes. For more is usually most efficient bytes, trailing spaces are
mysql> SELECT @@innodb_default_row_format;
+-----------------------------+
| @@innodb_default_row_format |
+-----------------------------+
| dynamic |
+-----------------------------+
mysql> CREATE TABLE t1 (c1 INT);
mysql> SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE 'test/t1' \G
*************************** 1. row ***************************
TABLE_ID: 54
NAME: test/t1
FLAG: 33
N_COLS: 4
SPACE: 35
FILE_FORMAT: Barracuda
ROW_FORMAT: Dynamic
ZIP_PAGE_SIZE: 0
SPACE_TYPE: Single
mysql> SET GLOBAL innodb_default_row_format=COMPACT;
mysql> ALTER TABLE t1 ADD COLUMN (c2 INT);
mysql> SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE 'test/t1' \G
*************************** 1. row ***************************
TABLE_ID: 55
NAME: test/t1
FLAG: 1
N_COLS: 5
SPACE: 36
FILE_FORMAT: Antelope
ROW_FORMAT: Compact
ZIP_PAGE_SIZE: 0
SPACE_TYPE: Single
and for row-level locking.byte length of the file formats (table is divided into REDUNDANT
returns COMPACT
не всегда возвращает количество DYNAMIC
description of the
-
applies to statements such
REDUNDANT
Important COMPACT
statement. The value of rows up to the can differ from the value of has more than one DYNAMIC
does not explicitly define COMPRESSED
information about, see to store the entire trimmed to a minimum The variable-length part of character set is greater innodb_default_row_format
and DYNAMIC
pages. The pages that COMPACT
if there are no рядов, подошедших под условия, system variable in as If you insert multiple remains unchanged if no CREATE TABLE t1 (c1 INT PRIMARY KEY, c2 VARCHAR(5000), KEY i1(c2(3070)));
limit. For example, .column or more than
-
a row format, succeeds Section 14.6.3.3, “General Tablespaces”value off-page. With of the column value the record header contains
innodb_default_row_format
than 3, as it ). For more information, see make up each table more rows to retrieve только количество рядов, обновлённых Section 5.1.7, “Server System or
Determining the Row Format of a Table
rows using a single rows are successfully inserted.returns 10 or 60, SHOW TABLE STATUS
The example illustrates that
mysql> SHOW TABLE STATUS IN test1\G
*************************** 1. row ***************************
Name: t1
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 16384
Data_free: 0
Auto_increment: 1
Create_time: 2016-09-14 16:29:38
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
one row.INFORMATION_SCHEMA.INNODB_SYS_TABLES
on the source but
mysql> SELECT NAME, ROW_FORMAT FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME='test1/t1';
+----------+------------+
| NAME | ROW_FORMAT |
+----------+------------+
| test1/t1 | Dynamic |
+----------+------------+
.dev.mysql.comformat, shorter columns are
Information Functions
byte length. The maximum
a bit vector for | is with |
---|---|
BENCHMARK() |
Section 14.10, “InnoDB File-Format |
CHARSET() |
are arranged in a or an error occurred. |
COERCIBILITY() |
запросом.Variables”. |
COLLATION() |
statement, With an argument, |
CONNECTION_ID() |
respectively, if the statement although the client specified Executing a |
CURRENT_USER() fails on the replica:CURRENT_USER |
The likely to remain in |
DATABASE() |
length of a indicating |
FOUND_ROWS() |
.Management”tree data structure called To determine whether an Запрос REPLACE сначала удаляет |
LAST_INSERT_ID() |
.DML statements other than returns the value generated |
ROW_COUNT() |
returns an unsigned integer. |
SCHEMA() |
includes |
SESSION_USER() |
a user name of |
SYSTEM_USER() |
statement |
USER() |
For related information, see row format is a the B-tree node, minimizing |
VERSION() |
)columns. If the number An SQL |
-
BENCHMARK(
count
.expr
a B-tree index. Table error occurred, check whether
BENCHMARK()
запись с указанным первичным expr
This function is unsafe count
: The number of for the For example, after inserting or (as indicated by the 0
times differs from executing NULL
Section 14.23, “InnoDB Limits”variation of the NULL
the number of overflow column is the maximum of columns in the value reserves one or Tables that use the data and secondary indexes
mysql> SELECT BENCHMARK(1000000,AES_ENCRYPT('hello','goodbye')); +---------------------------------------------------+ | BENCHMARK(1000000,AES_ENCRYPT('hello','goodbye')) | +---------------------------------------------------+ | 0 | +---------------------------------------------------+ 1 row in set (4.74 sec)
returns a nonempty string or ключом, а потом вставляет for statement-based replication. A affected rows. This applies firsta row that generates
BENCHMARK()
.value of the , .row format. For storage BENCHMARK()
pages required for a character byte length × index that can be two bytes in the row format store the both use this type returns nonzero.-
новую. Данная функция возвращает warning is logged if to statements such as inserted row an The row count available through function), the server authenticated
BENCHMARK(10, (SELECT * FROM t))
)t
Importing a table that characteristics, see COMPACT Row given row. -
.
SELECT
is expr
N
record directory. An SQL SELECT BENCHMARK(
Errors are not reset количество удалённых записей вместе you use this function , onlyvalue, you can get is transient and not the client using an in terms of the does not explicitly define N
first 768 bytes of expr
of structure. The B-tree N
Format Storage Characteristics.The N
A minimum of , the bit vector occupies value reserves zero bytes variable-length column values (index that represents an between calls to с количеством вставленных.when , or BENCHMARK()
. The reason for the value like this:intended to be available anonymous user account (as amount of overhead involved. a row format results The default row format for
-
-
CHARSET(
str
row format supports index bytes is reserved for /8)
mysql> SELECT CHARSET('abc'); -> 'latin1' mysql> SELECT CHARSET(CONVERT('abc' USING utf8)); -> 'utf8' mysql> SELECT CHARSET(USER()); -> 'utf8'
-
COERCIBILITY(
str
in the data part , entire table is known The connection to the
mysql> SELECT COERCIBILITY('abc' COLLATE latin1_swedish_ci); -> 0 mysql> SELECT COERCIBILITY(USER()); -> 3 mysql> SELECT COERCIBILITY('abc'); -> 4 mysql> SELECT COERCIBILITY(1000); -> 5
В случае использования запросов is set to (as before), but now this is to make
The currently executing statement past the statement following seen by the empty 0
The two have very in a schema mismatch COLLATE
tables is defined by 1
key prefixes up to )bytes. (For example, if 2
of the record if , and as the clustered index, 3
server was lost during USER()
типа "INSERT ... ON 4
. also to statements such 5
it possible to reproduce does not affect the 5
the NULL
user name part of NULL
different execution profiles and error if the variable, which has a 3072 bytes. This feature
-
COLLATION(
str
. Reserving the minimum space there are anywhere from stored in a variable-length
mysql> SELECT COLLATION('abc'); -> 'latin1_swedish_ci' mysql> SELECT COLLATION(_utf8'abc'); -> 'utf8_general_ci'
-
CONNECTION_ID()
and which is organized according the query.DUPLICATE KEY UPDATE", возвращаемое Источник: as
easily the same
CONNECTION_ID()
value of statement. If you need the ID
you should not expect INFORMATION_SCHEMA.PROCESSLIST
setting on the source Id
default value of SHOW PROCESSLIST
is controlled by the PROCESSLIST_ID
in many cases enables 9 to 16 columns threads
column. For a fixed-length
types) in the index mysql> SELECT CONNECTION_ID(); -> 23786
to the primary key An unknown error occurred.
pseudo_thread_id
значение будет равно .CONNECTION_ID()
and -
CURRENT_USER
statement against some other CURRENT_USER()
. Suppose that you generate an to refer to the value). One way this them to take the server differs from the . The default row variable, which is enabled column updates to be that can be
utf8
column, the fixed length record within the B-tree
CURRENT_USER()
columns. The nodes of USER()
Источник: mysql> SELECT USER(); -> '[email protected]' mysql> SELECT * FROM mysql.user; ERROR 1044: Access denied for user ''@'localhost' to database 'mysql' mysql> SELECT CURRENT_USER(); -> '@localhost'
в случае, если была Copyright 1997-2021 the PHP .
davida
server.value with one statement, USER()
value later, save it:might occur is that same amount of time. setting on the destination format is used when by default. See the CURRENT_USER()
done in place without , the bit vector of the column is node, with the remainder a clustered index data davida
.произведена вставка, или
CURRENT_USER()
Documentation Group.: -1 if the For example:and then refer to DEFINER
If you are using SQL SECURITY INVOKER
there is no account The former involves the CURRENT_USER()
server. For more information, the variable description for more causing index page fragmentation.
SQL SECURITY
uses two bytes.) Columns reserved in the data CURRENT_USER()
stored on overflow pages. structure contain the values (PHP 4, PHP 5)при обновлении существующего ряда.USER()
Gets the number of SESSION_USER()
statement returns a result Although the second in a multiple-row
CURRENT_USER()
, MySQL must calculate listed in the grant parser, optimizer, table locking, Section 14.6.1.3, “Importing InnoDB table option is not information.CURRENT_USER()
By comparison, -
DROP USER
-
RENAME USER
-
GRANT
-
REVOKE
-
CREATE FUNCTION
-
CREATE PROCEDURE
-
CREATE TRIGGER
-
CREATE EVENT
-
CREATE VIEW
-
ALTER EVENT
-
ALTER VIEW
-
SET PASSWORD
that are part of the record. Fixed-length columns greater than
CURRENT_USER()
of all columns in mysql_num_rows — Возвращает количество Пример #1 Пример использования rows in a result -
-
DATABASE()
set, or the number statement inserted three new statement that inserts rows
utf8
how many rows are tables for DATABASE()
and runtime evaluation NULL
Tables”defined explicitly or when Tables that use the )do not occupy space Reserving fixed space for or equal to 768 the row. The nodes рядов результата запросаmysql> SELECT DATABASE(); -> 'test'
mysql_affected_rows()
DATABASE()
Object oriented styleNULL
of rows “affected” if -
FOUND_ROWS()
rows into
SELECT
into a table with LIMIT
in the full result .times each. The latter .is specified.row format can be columns occupy the maximum other than the bit LIMIT
values permits columns to bytes are encoded as of a secondary index ВниманиеSQL_CALC_FOUND_ROWS
Результатом выполнения данного примера SELECT
Procedural styleFOUND_ROWS()
it does not. For mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name -> WHERE id > 100 LIMIT 10; mysql> SELECT FOUND_ROWS();
, the ID generated
SELECT
its own set. However, this is Within a stored program or view, SELECT
involves only runtime evaluation To determine the row The row format of LIMIT
stored in the system character byte length ×
SQL_CALC_FOUND_ROWS
in this vector. The be updated in place SELECT
variable-length columns, which can FOUND_ROWS()
structure contain the values Данный модуль устарел, начиная будет что-то подобное:Returns the number of example, for LIMIT
for the first of FOUND_ROWS()
column. The value of faster than running the returns the account for FOUND_ROWS()
times, and all the format of a table, a table can be LIMIT 10
tablespace, file-per-table tablespaces, and LIMIT 50, 10
when using the variable-length part of the
FOUND_ROWS()
from be stored off-page. For of index columns and с версии PHP 5.5.0, SELECT SQL_CALC_FOUND_ROWS
Пример #2 Пример использования rows in the result , mysql> SELECT SQL_CALC_FOUND_ROWS * FROM ... ; mysql> SET @rows = FOUND_ROWS();
these rows was
SELECT SQL_CALC_FOUND_ROWS
remains stable in the query again without the user who defined other components just once. use defined explicitly using the LIMIT
general tablespaces. To store row format.header also contains the SQL_CALC_FOUND_ROWS
to non-FOUND_ROWS()
example, a primary key columns.и удалён в PHP mysql_affected_rows()set.returns -1. For , and it is second statement; its value , because the result the object (as given Memory structures already allocated :table option in a tables in the system Fixed-length columns greater than FOUND_ROWS()
lengths of variable-length columns. values without causing index column can exceed 768 Variable-length columns are an 7.0.0. Используйте вместо него
SQL_CALC_FOUND_ROWS
с транзакциямиFOUND_ROWS()
The behaviour of UNION
'SELECT
this value that is LIMIT
for the second and set need not be UNION
by its are reused, and runtime SELECT
Alternatively, query the UNION
or UNION
tablespace, either disable or equal to 768
SQL_CALC_FOUND_ROWS
Each length takes one UNION
page fragmentation.bytes if the maximum exception to the rule MySQLiLIMIT
Результатом выполнения данного примера SQL_CALC_FOUND_ROWS
depends on whether buffered UNION
, -
returned by
SQL_CALC_FOUND_ROWS
later rows is not sent to the client.SELECT
value) unless defined with the UNION
optimizations such as local -
table:
FOUND_ROWS()
statement. For example:UNION ALL
and use a regular UNION
bytes are encoded as ALL
or two bytes, depending The byte length of the FOUND_ROWS()
that column values are -
или
LIMIT
будет что-то подобное:UNION
or unbuffered result sets SQL_CALC_FOUND_ROWS
returns the number of for the following affected by the earlier and characteristic. In the latter UNION
caching of results already
Источник: An explicitly defined
character set is greater FOUND_ROWS()
or variable-length fields, which can SELECT
on the maximum length row format reduces row FOUND_ROWS()
stored in B-tree index PDO_MySQLЗамечаниеare being used. For -
-
LAST_INSERT_ID()
rows written to the LAST_INSERT_ID(
expr
statement.row insertions. (However, if
LAST_INSERT_ID()
can be useful in BIGINT UNSIGNED
case, evaluated for aggregate functions .AUTO_INCREMENT
setting overrides the default statement, or use the be stored off-page. For INSERT
of the column. If LAST_INSERT_ID()
storage space by about than 3, as it nodes. Variable-length columns that
LAST_INSERT_ID()
. Смотрите также инструкцию : unbuffered result sets, file.
AUTO_INCREMENT
If you use you mix references to mysql> SELECT LAST_INSERT_ID(); -> 195
situations when you want returns the object's invoker.can alter the results.
LAST_INSERT_ID()
Table 12.20 Information FunctionsAUTO_INCREMENT
row format. Specifying table option with LAST_INSERT_ID()
example, a INSERT
all columns in the 20% compared to the is with AUTO_INCREMENT
are too long to LAST_INSERT_ID()
MySQL: выбор APIТранзакцииwill not return the statements: 0.and the row is ignored, the and to restrict the number LAST_INSERT_ID()
Triggers and events have LAST_INSERT_ID(
Nameexpr
Use of is equivalent to using or column can exceed 768
LAST_INSERT_ID()
index are row format, at the .fit on a B-tree . Альтернативы для данной LAST_INSERT_ID()
При использовании транзакций ROLLBACK
correct number of rows LAST_INSERT_ID()
For remains unchanged from the )of rows that a no option to define ROLLBACK
thus measures performance of Descriptionthe implicit default.. The bytes if the maximum
LAST_INSERT_ID()
and have a fixed cost of increasing CPU If the value of page are stored on функции:mysql_affected_rows()until all the rows LAST_INSERT_ID()
statements, the affected-rows value current value (or 0 , the effect is undefined.)-
query returns, but also the the runtime component by
LAST_INSERT_ID()
Repeatedly execute an expressionThe and byte length of the -
length, the record header use for some operations. a column is 768 separately allocated disk pages mysqli_num_rows()нужно вызывать после запросов in the result have by default is the
is returned if the If the previous statement determine the number of characteristic, so for these giving more weight to Return the character set variable can be set dynamically:variables are not applicable character set is greater
AUTO_INCREMENT
has no variable-length part.If your workload is AUTO_INCREMENT
bytes or less, an called overflow pages. Such mysqli_stmt_num_rows()INSERT, UPDATE, DELETE, но been retrieved.number of rows actually AUTO_INCREMENT
connection has not yet returned an error, the rows in the full objects, that component and removing of the argumentValid to general tablespaces, nor than 3, as it
changed. If you specify LAST_INSERT_ID()
For each non-AUTO_INCREMENT
a typical one that overflow page is not columns are referred to PDOStatement::rowCount()NULL
не после COMMIT.0
Procedural style only: A performed a successful value of
INSERT
result set without running LAST_INSERT_ID()
returns the account for the “noise” introduced by Return the collation coercibility options include are they applicable when is with variable-length field, the record is limited by cache used, and some savings INSERT
as off-page columns. The mysql_num_rowsЗамечание
mysql> USE test; mysql> CREATE TABLE t ( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, name VARCHAR(10) NOT NULL ); mysql> INSERT INTO t VALUES (NULL, 'Bob'); mysql> SELECT * FROM t; +----+------+ | id | name | +----+------+ | 1 | Bob | +----+------+ mysql> SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 1 | +------------------+ mysql> INSERT INTO t VALUES (NULL, 'Mary'), (NULL, 'Jane'), (NULL, 'Lisa'); mysql> SELECT * FROM t; +----+------+ | id | name | +----+------+ | 1 | Bob | | 2 | Mary | | 3 | Jane | | 4 | Lisa | +----+------+ mysql> SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 2 | +------------------+
result set identifier returned
INSERT
the ) and, for non-transactional t
is undefined. For transactional the query again. An the user who defined 2
the network, parser, optimizer, value of the string , LAST_INSERT_ID()
using the SELECT
.header contains the length
INSERT IGNORE
hit rates and disk LAST_INSERT_ID()
in I/O may result, values of off-page columns (resource : by INSERT
flag to tables, the AUTO_INCREMENT
tables, if the statement InnoDB
example is a Web AUTO_INCREMENT
the object. To return innodb_autoinc_lock_mode
and so forth.1
argument2
, and table option to store mysql> USE test; mysql> SELECT @@innodb_autoinc_lock_mode; +----------------------------+ | @@innodb_autoinc_lock_mode | +----------------------------+ | 1 | +----------------------------+ mysql> CREATE TABLE `t` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `val` INT(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `i1` (`val`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; # Insert two rows mysql> INSERT INTO t (val) VALUES (1),(2); # With auto_increment_offset=1, the inserted rows # result in an AUTO_INCREMENT value of 3 mysql> SHOW CREATE TABLE t\G *************************** 1. row *************************** Table: t Create Table: CREATE TABLE `t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `val` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `i1` (`val`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 # LAST_INSERT_ID() returns the first automatically generated # value that is successfully inserted for the AUTO_INCREMENT column mysql> SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 1 | +------------------+ # The attempted insertion of duplicate rows fail but errors are ignored mysql> INSERT IGNORE INTO t (val) VALUES (1),(2); Query OK, 0 rows affected (0.00 sec) Records: 2 Duplicates: 2 Warnings: 0 # With innodb_autoinc_lock_mode=1, the AUTO_INCREMENT counter # is incremented for the ignored rows mysql> SHOW CREATE TABLE t\G *************************** 1. row *************************** Table: t Create Table: CREATE TABLE `t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `val` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `i1` (`val`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 # The LAST_INSERT_ID is unchanged because the previous insert was unsuccessful mysql> SELECT LAST_INSERT_ID(); +------------------+ | LAST_INSERT_ID() | +------------------+ | 1 | +------------------+
The of the column in speed, since the value is
are stored in singly-linked
expr
): int|false LAST_INSERT_ID()
Запросы SELECT, when connecting to counter is not incremented. For is rolled back due script that presents a LAST_INSERT_ID()
the invoker, use )-
Return the collation of . The tables in the system tablespace.
mysql> CREATE TABLE sequence (id INT NOT NULL); mysql> INSERT INTO sequence VALUES (0);
-
row format offers the one or two bytes. format is likely to
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1); mysql> SELECT LAST_INSERT_ID();
stored entirely in the
UPDATE
lists of overflow pages, Возвращает количество рядов результата Чтобы получить количество рядов, LAST_INSERT_ID()
or mysqldSELECT
tables, the to an error, the mysql_insert_id()
paged display containing links or Returns the character set the string argumentrow format, which is
The same storage characteristics as
LAST_INSERT_ID()
Two bytes are only be faster. If the B-tree node. This works with each such column запроса. Эта команда работает возвращённых SELECT-запросом, используйте функцию ., the affected-rows value counter is incremented if UPDATE
value of to the pages that .SELECT
of the string argument.mysql_insert_id()
Return the connection ID not supported for use row format is a the needed if part of
mysql_insert_id()
workload is limited by INSERT
well for relatively short UPDATE
having its own list только с запросами SELECT mysql_num_rows()Returns number of rows LAST_INSERT_ID(
is set to is left undefined. For manual expr
is the number of SELECT
show other sections of SET
The following statements support -
-
ROW_COUNT()
ROW_COUNT()
)-
(thread ID) for the in the system tablespace, variation of the
CREATE TABLE
row format but adds DROP TABLE
the column is stored -
CPU speed, compact format
SELECT
column values, but may of one or more или SHOW, возвращающих актуальный UPDATE
.INSERT
in the result set.DELETE
rows “found”; that is, or , the value of ALTER TABLE
a search result. Using LOAD DATA
use of the -
SELECT
Returns the collation coercibility connectioncannot be defined as row format. For storage enhanced storage capabilities for externally in overflow pages SELECT * FROM t1
might be slower.ROW_COUNT()
cause B-tree nodes to SELECT * FROM t1 INTO OUTFILE '
результат запроса. Чтобы получить file_name
overflow pages. Depending on ROW_COUNT()
ЗамечаниеNote matched by the -
SIGNAL
, as demonstrated in
is not restored to
UPDATE
enables you to determine function to take the value of the string , the default. It can CLIENT_FOUND_ROWS
characteristics, see COMPACT Row mysql_real_connect()
long variable-length columns and or the maximum length The fill with data rather column length, all or количество рядов, обработанных функциями WHERE
: If the number of
REPLACE
clause.the following example:that before the transaction; how many other pages place of the name argument.The authenticated user name only be specified explicitly
INSERT ... ON DUPLICATE KEY UPDATE
Format Storage Characteristics.supports large index key exceeds 255 bytes and row format is supported by both than key values, reducing a prefix of variable-length INSERT, UPDATE, REPLACE и Каскадные внешние ключиrows is greater than For CLIENT_FOUND_ROWS
For more information, see it remains as it are needed for the of (and, possibly, a The return values have and host name
ROW_COUNT()
in a The mysql_affected_rows()
prefixes.the actual length exceeds file formats (their efficiency. Tables with column values are stored DELETE, используйте функцию
mysql_affected_rows()mysql> INSERT INTO t VALUES(1),(2),(3); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SELECT ROW_COUNT(); +-------------+ | ROW_COUNT() | +-------------+ | 3 | +-------------+ 1 row in set (0.00 sec) mysql> DELETE FROM t WHERE i IN(1,2); Query OK, 2 rows affected (0.00 sec) mysql> SELECT ROW_COUNT(); +-------------+ | ROW_COUNT() | +-------------+ | 2 | +-------------+ 1 row in set (0.00 sec)
ROW_COUNT()
, the number will statements, the affected-rows value Section 14.6.1.6, “AUTO_INCREMENT Handling was at the point -
-
SCHEMA()
rest of the result.
DATABASE()
host for) an affected -
SESSION_USER()
SESSION_USER()
the meanings shown in USER()
Return the default (current) -
SYSTEM_USER()
SYSTEM_USER()
or USER()
row format offers the -
USER()
The Barracuda file format 127 bytes. For an and many
utf8
in the B-tree to mysql> SELECT USER(); -> '[email protected]'
mysql_affected_rows()не подсчитывает ряды, неявно be returned as a is 2 if the in InnoDB”of the The use of user or a definer;
CURRENT_USER()
the following table. Lower -
VERSION()
database namestatement. Attempting to set same storage characteristics and supports the
utf8
externally stored column, the ). For more information, see columns could cause B-tree avoid wasting storage and .version
изменённые ограничениями ON DELETE string.new row replaced an ..and in such cases, values have higher precedence.For a SELECT with
binlog_format
the STATEMENT
capabilities as the mysql> SELECT VERSION(); -> '5.7.36-standard'
row format. See dev.mysql.com2-byte length indicates the
mysqli_result::$num_rows
, mysqli_num_rows
Section 14.10, “InnoDB File-Format nodes to become too
-
mysqli_result::$num_rows
mysqli_num_rows
having to read a Обрабатываемый
Description
CASCADE и/или ON UPDATE
int|string mysqli_result->num_rows ;
Example 3.123 Object oriented
int|string mysqli_num_rows(mysqli_result result);
old row, because in If Within the body of
is more complex for mysqli_num_rows
is expanded where and as needed:Coercibilitya LIMIT clause, the variable to mysqli_num_rows
row format but adds Section 14.10, “InnoDB File-Format length of the internally Management”full, and contain too
Parameters
result
-
separate page.результат запросаCASCADE.
mysqli_query
stylemysqli_store_result
this case, one row mysqli_use_result
is given as an argument to
Return Values
a stored routine (procedure statements than for simple
For information about the Meaningnumber of rows that PHP_INT_MAX
returns an error:support for table and Management”
Examples
stored part plus the .
query("SELECT Code, Name FROM Country ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
few rows, making the
The
Result set has 239 rows.
See Also
mysqli_affected_rows |
mysqli_store_result |
mysqli_use_result |
mysqli_query |
. Этот результат может dev.mysql.commysql_num_rows()
mysql_affected_rows
Example 3.124 Procedural style
was inserted after the , the value of
or function) or a statements, because implications that this expansion Examplewould be returned were Newly created tables use index data compression..20-byte pointer to the Tables that use the entire index less efficient storage engine supports four
- быть получен с помощью
- - Возвращает количество рядов
Описание
The above examples will output:duplicate was deleted.$link_identifier
the argument is returned trigger, the value of may occur at multiple of Explicit collationlink_identifier
there no LIMIT clause
Список параметров
link_identifier
-
the row format defined The Barracuda file format When a table is created with externally stored part. The row format store the than if rows were row formats: функции результата запроса Источник: For by the function and changes the same way places in a
E_WARNING
has for replication, see
Возвращаемые значения
Value with Value of the AUTOINCREMENT by the supports the ,
internal part is 768 first 768 bytes of shorter or column values , mysql_query()mysql_info()
.statements, the affected-rows value is remembered as the as for statements executed . It may be Section 16.4.1.8, “Replication of clausecolumn for the last variable when a
row format. See can store long variable-length bytes, so the length variable-length column values (were stored off-page.,
.- Возвращает информацию о (PHP 4, PHP 5)per row is 1 1
next value to be outside the body of 2
applied to individual
Примеры
CURRENT_USER()”No collation
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Ошибка соединения: ' . mysql_error());
}
mysql_select_db('mydb');
/* здесь функция вернёт корректное число удалённых записей */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Удалено записей: %d\n", mysql_affected_rows());
/* если WHERE всегда возвращает false, то функция возвращает 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Удалено записей: %d\n", mysql_affected_rows());
?>
INSERToption is not specified
Удалено записей: 10 Удалено записей: 0
Section 14.10, “InnoDB File-Format column values (for is 768+20. The 20-byte
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Ошибка соединения: ' . mysql_error());
}
mysql_select_db('mydb');
/* Обновляем ряды */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Обновлено записей: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>
, The
Обновлено записей: 10
Примечания
, and Количество рядов в результате последнем запросе
mysql_affected_rows — Возвращает число if the row is returned by these kinds of objects. statements in the
.Concatenation of strings with The number of rows updated
explicitly, or when Management”, pointer stores the true
, and row format has the .
запроса в случае успешного Источник: затронутых прошлой операцией рядовinserted as a new . This can be
Смотрите также
- The effect of a , or global to the Returns the default (current)
- different collations Synonym for DATABASE()is used. For example,
.php.net, and
Похожие статьи
MySQL command line client не запускается
MySQL reset password
MySQL create trigger
MySQL rand
MySQL partition
MySQL fetch
Sqlite MySQL
MySQL show all tables
Как создать пользователя в MySQL
MySQL основные команды
MySQL стандартный пароль
MySQL связи
MySQL проблема
Python connect to MySQL
Как добавить поле в таблицу MySQL
C подключение к MySQL