Friday, January 7, 2011

How to Fetch an Array in MySQL


Technically there is no "fetch array" function in MySQL. It's a PHP function that interacts with a MySQL database. MySQL databases are not very useful if application code can't have easy access to the data returned. PHP provides some easy functions to get at data returned by MySQL.

Instructions

    Query the MySQL Database

  1. 1
    Open a connection to the MySQL server. This is a simple call to mysql_connect, which returns a MySQL resource. Store this resource in a variable. Example:
    $mysql = mysql_connect("localhost", "my_user", "my_password");
  2. 2
    Select a database. This requires a call to mysql_select_db. Example:
    mysql_select_db($mysql, "customers_db");
  3. 3
    Form a query. Many times, queries are non-trivial, as you might have several variables being expanded in a very long query string. It's best to format that string outside of the call to mysql_query. It's best to use sprintf and mysql_escape_string to prevent such errors as query failures or data compromises. In this example, the $name and $ph_number variable have come from a web form. Example:
    $query = sprintf( "SELECT * FROM customers WHERE name='%s' AND ph_numbers='%s'",
    mysql_escape_string($name), mysql_escape_string($ph_number) );
  4. 4
    Submit the query. This is done with the mysql_query function. It takes a MySQL resource and a query string as an argument and returns a MySQL result handle. From this handle, you can fetch rows one at a time. Should the query fail, mysql_query will return FALSE and you will be able to access an error message by calling the mysql_error function. Example:
    $result = mysql_query($mysql, $query);
    if(!$result) {
    die( "Invalid query: " . mysql_error() );
    }
  5. Fetch the Result as a Numeric Array

  6. 1
    Fetch the result as a numeric array with mysql_fetch_array. The columns of the result will be in order, the first column having an index of 0.
  7. 2
    Call this function multiple times to get the next row. If there are no more rows remaining in the result resource, mysql_fetch_array will return FALSE. Example:
    $row = mysql_fetch_array($result);
  8. Fetch the Result as an Associative Array

  9. 1
    Fetch the result as an associative array with mysql_fetch_assoc. This function returns an associative array with keys equal to the column names. For example, if you wanted to access the name field of a row, you'd simply need to call $row["name"].
  10. 2
    Realize that this will not change if the number or order of columns in the table changes via an ALTER SQL command. Like all the other mysql_fetch_* functions, you can call it repeatedly to get more rows from the result. It'll return FALSE when there are no more rows in the result. Example:
    $row = mysql_fetch_assoc($result);


No comments:

Post a Comment