Databases Reference
In-Depth Information
mixed mysqli_query(resource
connection
, string
query
)
Executes an SQL query on a connection. This is conceptually the same as typing
an SQL query into the MySQL monitor and pressing the Enter key. The first pa-
rameter is a
connection
resource handle that was returned from
mysqli_connect(
)
and the second is an SQL
query
; note that the parameter order is the opposite of
the original MySQL library's
mysql_query( )
function.
The function does not return or display the results. Instead, for
SELECT
,
SHOW
,
EXPLAIN
, or
DESCRIBE
queries, it returns a
resource handle
that can be assigned to a
variable and used to access the results. The
mysqli_fetch_array( )
function dis-
cussed next is usually used for this task. For
UPDATE
,
INSERT
,
DELETE
, and other
queries that do not produce output, the return value is either
true
(indicating suc-
cess) or
false
(indicating failure). Note that you don't need to include a semicolon
(
;
) at the end of the query string, though there are no problems if you do.
array mysqli_fetch_array(resource
result
[, int
type
])
Returns an array containing one row of results from a previously executed query.
The
result
handle parameter is the return value from a previously-executed
mysqli_query( )
function. Each call to the function returns the next available row
of results as an array, with
false
returned when no further rows are available. This
function is explained in detail later in “Accessing Query Results with
mysql_fetch_array(
) and mysqli_fetch_array(
).”
The three previous functions are sufficient to build simple applications. The three
functions discussed next are also important, and you'll find them helpful in all but the
most basic applications.
When you run queries, the MySQL monitor reports useful information that helps you
make decisions about what to do next. To access this information from PHP scripts,
you need to use functions. Three functions you'll find useful are:
int mysqli_insert_id(resource
connection
)
If you use the
AUTO_INCREMENT
feature, this function allows you to access the unique
identifier value associated with the most recent
INSERT
statement on a connection.
The database
connection
is passed as a parameter, and the return value is an integer
that uniquely identifies the new row. A value of 0 is returned if
AUTO_INCREMENT
wasn't used by the most recent query.
int mysqli_affected_rows(resource
connection
)
Reports the number of rows that were modified by the last query on the connection
identified by the resource handle
connection
. We describe this function in more
detail later in “Finding the Number of Changed Rows Using mysql_affected_rows
and mysqli_affected_rows.”
int mysqli_num_rows(resource
result
)
Reports the number of rows returned by a
SELECT
query identified by a
result
resource handle. The function doesn't work for queries that modify the database;
mysqli_affected_rows( )
should be used there instead.