Databases Reference
In-Depth Information
mixed mysql_query(string
query
, resource
connection
)
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 an SQL
query
, and the second is a connection resource handle that was
returned from
mysql_connect( )
.
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
mysql_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. In the
MySQLi library, the order of the parameters is reversed.
array mysql_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
mysql_query( )
function, and the optional
type
controls what type of array is re-
turned; this is discussed later in this chapter in “Accessing Query Results with
mysql_fetch_array(
) and mysqli_fetch_array(
).” Each call to the function returns
the next available row of results as an array, with
false
returned when no further
rows are available.
The four previous functions are sufficient to build simple applications. The three func-
tions 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 mysql_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 mysql_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.”