Executing SQL Statements


The function to pass a SQL statement to MySQL is mysql_query. It takes two argumentsthe query itself and an optional link identifier.

The following code executes a CREATE TABLE SQL statement on the MySQL database for $db:

 $sql = "CREATE TABLE mytable (col1 INT, col2 VARCHAR(10))"; mysql_query($sql, $conn); 

If you run a script that contains these statements in your web browser and check your MySQL database, you will find that a new table called mytable has been created.

All types of SQL statement can be executed through mysql_query, whether they alter the data in some way or fetch a number of rows.

Commands That Change a Database

Earlier in this lesson you saw an example of a CREATE TABLE statement. Other Data Definition Language (DDL) statements can be executed in a similar fashion, and, provided that no errors are encountered, they perform silently. You will learn about error handling later in this lesson.

When executing a DELETE, INSERT, or UPDATE statementa subset of SQL known as the Database Manipulation Language (DML)a number of rows in the table may be affected by the query. To find out how many rows are actually affected, you can use the mysql_affected_rows function. The following example shows how to do this with a simple UPDATE statement:

 $sql = "UPDATE mytable SET col2 = 'newvalue' WHERE col1 > 5"; mysql_query($sql, $conn); echo mysql_affected_rows($conn) . " row(s) were updated"; 

The argument to mysql_affected_rows is the database link identifier, and a call to this function returns the number of rows affected by the most recent query. The number of rows affected by this UPDATE statement is not necessarily the number of rows matching the WHERE clause. MySQL does not update a row if the new value is the same as the one already stored.

Deleting All Rows If you execute a DELETE statement with no WHERE clause, the number returned by mysql_affected_rows is zero, regardless of the number of rows actually deleted. MySQL simply empties the table rather than delete each row in turn, so no count is available.


Fetching Queried Data

The SELECT statement should return one or more rows from the database, so PHP provides a set of functions to make this data available within a script. In order to work with selected data, you must assign the result from mysql_query to a result resource identifier, as follows:

 $res = mysql_query($sql, $db); 

You cannot examine the value of $res directly. Instead, you pass this value to other functions to retrieve the database records.

You can use the function mysql_result to reference a data item from a specific row and column number in the query result. This is most useful when your query will definitely only return a single valuefor instance, the result of an aggregate function.

The following example performs a SUM operation on the elements in a table column and displays the resulting value onscreen:

 $sql = "SELECT SUM(col1) FROM mytable"; $res = mysql_query($sql, $conn); echo mysql_result($res, 0, 0); 

The three arguments to mysql_result are the result resource identifier, a row number, and a column number. Numbering for both rows and columns begins at zero, so this example finds the first row in the first column in the result set. In fact, because of the nature of aggregate functions, you can be sure that there will always be only a single row and column in the result of this query, even if there are no records in the table. An attempt to access a row or column number that does not exist will result in an error.

The function mysql_num_rows returns the number of rows found by the query, and you can use this value to create a loop with mysql_result to examine every row in the result. The following code shows an example of this:

 $sql = "SELECT col1, col2 FROM mytable"; $res = mysql_query($sql, $db); for ($i=0; $i < mysql_num_rows($res); $i++) {   echo "col1 = " . mysql_result($res, $i, 0);   echo ", col2 = " . mysql_result($res, $i, 1) . "<br>"; } 

With the query used in this example, because the column positions of col1 and col2 are known, you can use mysql_result with a numeric argument to specify each one in turn.

Field Names You can use a string for the column argument to mysql_result; in this case, you need to give the column's name. This behavior is particularly useful in SELECT * queries, where the order of columns returned may not be known, and in queries where the number of columns returned is not easily manageable.


Fetching Full Rows of Data

PHP provides a convenient way to work with more than one item from a selected row of data at a time. By using mysql_fetch_array, you can create an array from the query result that contains one element for each column in the query.

When you call mysql_fetch_array on a result resource handle for the first time, an array is returned that contains one element for each column in the first row of the data set. Subsequent calls to mysql_fetch_array cause an array to be returned for each data row in turn. When there is no more data left to be fetched, the function returns FALSE.

You can build a very powerful loop structure by using mysql_fetch_array, as shown in the following example:

 $sql = "SELECT col1, col2 FROM mytable"; $res = mysql_query($sql, $conn); while ($row = mysql_fetch_array($res)) {   echo "col1 = " . $row["col1"];   echo ", col2 = " . $row["col2"] . "<br>"; } 

Each row of data is fetched in turn, and in each pass of the loop, the entire row of data is available in the array structure, without any further function calls being necessary.

The array contains the row's data, using elements with both numeric and associative indexes. In the previous example, because you know that col1 is the first column selected, $row["col1"] and $row[0] contain the same value.

This mechanism provides a method of sequential access to every row returned by a query. Random access is also available, and by using the function mysql_data_seek, you can specify a row number to jump to before the next mysql_fetch_array is performed.

To jump to the tenth row, you would use the following (remember that the numbering begins at zero, not one):

 mysql_data_seek($res, 9); 

It therefore follows that to reset the row position to the start of the data set, you should seek row zero:

 mysql_data_seek($res, 0); 

If you attempt to call mysql_data_seek with a row number that is higher than the total number of rows available, an error occurs. You should check the row number against the value of mysql_num_rows to ensure that it is valid.

Seeking To skip to the last row of a data set, you call mysql_data_seek($res, mysql_num_rows($res)-1). The number of the last row is one less than the total number of rows in the result.

However, the result can usually be achieved more easily by specifying reverse sorting in an ORDER BY clause in your SQL and selecting the first row instead.




    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net