home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeManaging and Using MySQLSearch this book

18.2. Functions

mysql_connect

cresource mysql_connect([string hostname [, string username [, string password 
[, boolean new_connection]]]])

Used to establish a connection to the MySQL DBMS. The function returns a connection resource handle on success that can be used to access databases through subsequent function calls. The function returns false on failure.

The function has four optional parameters. The first is the hostname of the DBMS that can include an optional port number. The hostname parameter is usually set to localhost when the MySQL DBMS and the web server are running on the same machine. A default port for MySQL of 3306 is assumed if the port is omitted.

The second and third parameters—a username and password—are MySQL DBMS username and password credentials. These are the same username and password used to access the DBMS though the command-line monitor mysql.

If a second call is made to the function in the same script with the same first three parameters, a new connection is not opened. Instead, the function just returns the connection resource handle of the existing open connection. In the upcoming PHP 4.2 release, you should be able to override this behavior by supplying a fourth new_connection parameter. When it is set to true, a new connection will always be opened.

If all parameters are omitted, the hostname and port default to localhost:3306, the username defaults to the name of the user that owns the MySQL DBMS server process, and the password defaults to an empty string. Because these parameters are unlikely to be valid credentials for accessing the MySQL DBMS, the first three parameters to mysql_connect( ) should be supplied in practice.

Example

<?php
  
  // This is a typical function call
  // Local machine, user "fred" and password "shhh"
  // On a Unix machine, this defaults to Unix socket
  $connection1 = mysql_connect("localhost", "fred", "shhh");
  
  // Local machine, user "fred" and password "shhh"
  // Adding the port forces a TCP/IP connection
  // on a Unix machine
  $connection2 = mysql_connect("localhost:3306", "fred", "shhh");
  
  // Remote machine "blah.webdatabasebook.com" on port 4000
  $connection3 = mysql_connect("blah.webdatabasebook.com:4000", "fred", "shhh");
  
?>
mysql_fetch_array

array mysql_fetch_array (qresource query [, int array_type])

Returns an array that contains the next available row from the result set associated with the parameter query. The internal pointer associated with the result set is then incremented, so that the next call to this function will retrieve the next row. The query resource handle is returned from a prior call to mysql_query( ) or mysql_unbuffered_query( ). The function returns false when no more rows are available.

Each row is returned as an array, and all elements of the array are of type string. The second parameter, array_type, controls whether associative access, numeric access, or both are possible on the array. When set to MYSQL_ASSOC, the function behaves identically to mysql_fetch_assoc( ). When set to MYSQL_NUM, the function behaves identically to mysql_fetch_row( ). The default is MYSQL_BOTH, which permits both associative and numeric array access.

If two or more attributes in the query have the same name, only the last-named attribute in the SELECT clause is available via the associative array. The other attributes with identical names must be accessed via their numeric indexes.

When both a table and attribute name are used in a SELECT statement, only the attribute name should be used to access the data associatively. For example, after executing the statement SELECT p.quantity FROM presents p, the attribute data is accessed associatively in the array $row that is returned from mysql_fetch_array( ) as $row["quantity"].

Attributes can be aliased and then retrieved using the alias name. For example, consider the following statement:

SELECT customer.cust_id AS c, 
       orders.cust_id AS o 
FROM orders, customer 
WHERE customer.cust_id = orders.cust_id

The attribute data can be accessed in an associate array $row that is returned from mysql_fetch_array( ) as $row["c"] and $row["o"].

Aggregate functions are associatively referenced using the aggregate function name. For example, after executing the statement SELECT sum(quantity) FROM presents, the aggregate data is accessed associatively in the array $row that is returned from mysql_fetch_array( ) as $row["sum(quantity)"].

NOTE: Prior to PHP 4.0.5, NULL values were not returned into the array, but this has been fixed in recent versions.

This bug doesn't affect associative access, but it causes renumbering for numeric access. If a table has a NULL attribute, the array returned has one fewer element. The missing element can still be referenced associatively, because referencing a nonexistent element correctly returns NULL. However, if you want to avoid having arrays of different lengths returned, ensure that all attributes have a value or upgrade to a new release of PHP.

Example

<?php
  $query = "SELECT * FROM presents";
  
  $connection = mysql_connect("localhost", "fred", "shhh");
  mysql_select_db("wedding", $connection);
  
  $result = mysql_query($query, $connection);
  
  while ($row = mysql_fetch_array($result))
  {
     echo "ID:\t{$row["present_id"]}\n";
     echo "Quantity:\t{$row["quantity"]}\n";
     echo "Present:\t{$row["present"]}\n";   
     echo "Shop:\t{$row["shop"]}\n\n";
  }
?>
mysql_fetch_field

object mysql_fetch_field(qresource query [, int attribute ])

Returns an object containing metadata about an attribute associated with a query resource handle. The first argument is a query resource handle returned from a prior call to mysql_list_fields( ), mysql_query( ), or mysql_unbuffered_query( ). The second optional parameter indicates which attribute in the result set is required. If no second argument is provided, metadata about the first attribute that has not yet been retrieved is returned. Thus, successive calls to mysql_fetch_fields( ) can be used to retrieve information about all the attributes in a query result set.

The properties of the object returned by the function are:

name
The attribute name

table
The name of the table to which the attribute belongs

max_length
The maximum length of the attribute

not_null
Set to one if the attribute cannot be NULL

primary_key
Set to one if the attribute forms part of a primary key

unique_key
Set to one if the attribute is a unique key

multiple_key
Set to one if the attribute is a non-unique key

numeric
Set to one if the attribute is a numeric type

blob
Set to one if the attribute is a BLOB type

type
The type of the attribute

unsigned
Set to one if the attribute is an unsigned numeric type

zerofill
Set to one if the numeric column is zero filled

Example

<?php
  $connection = mysql_connect("localhost", "fred", "shhh");
  
  $result = mysql_list_fields("wedding", "presents");
  
  echo "Presents table attributes:\n";
  
  while ($row = mysql_fetch_field($result))
  {
     echo $row->name;          
     echo " is an attribute of type " . $row->type . ".";
     if ($row->not_null == true)
        echo " It cannot be null.\n";
     else
        echo " It can be null.\n";
  }
?>
mysql_fetch_object

object mysql_fetch_object(qresource query [, int array_type])

Returns an object that contains the next available row from the result set associated with the parameter query. The internal pointer associated with the result set is then incremented, so that the next call to this function will retrieve the next row. The query resource handle is returned from a prior call to mysql_query( ) or mysql_unbuffered_query( ). The function returns false when no more rows are available.

Each row is returned as an object, and all member variables of the object are of type string. The second parameter array_type should be included and set to MYSQL_ASSOC. Numeric indexes cannot be used to access objects.

The same associative access limitations that apply to mysql_fetch_array( ) apply to mysql_fetch_object( ). There is one additional limitation: aggregate functions must be aliased for associative access, because parentheses and other special characters are invalid in member variable names. Thus, the sum( ) function in the statement SELECT sum(quantity) as total FROM presents can be accessed associatively in the object $row as $row->total.

Example

<?php
  $query = "SELECT * FROM presents";
  
  $connection = mysql_connect("localhost", "fred", "shhh");
  mysql_select_db("wedding", $connection);
  
  $result = mysql_query($query, $connection);
  
  while ($row = mysql_fetch_object($result, MYSQL_ASSOC))
  {
     echo "\n\nQuantity:\t" . $row->quantity;
     echo "\nPresent:\t" . $row->present;
     echo "\nShop:\t" . $row->shop;
  }
?>
mysql_pconnect

cresource mysql_pconnect([string hostname [, string username [, string password]]])

Used to establish or re-establish a connection to the MySQL DBMS. The function returns a connection resource handle on success that can be used to access databases through subsequent function calls. The function returns false on failure. The three parameters are identical to the first three parameters of mysql_connect( ).

This function should be called only once with the same parameters in a script: any subsequent calls to mysql_pconnect( ) in the same script with the same parameters return the same connection handle. Indeed, connections created with mysql_pconnect( ) are often reused across several scripts: the p stands for persistent, which means that after the script ends, the connection is kept in a pool. The connection can then be reused by any other script that requires a connection with the same hostname, username, and password.

Connections in the pool that remain unused are closed to save resources. How long a connection can remain unused is a MySQL parameter and is set to a default of five seconds. This can be changed with the --set-variable connect_timeout parameter to safe_mysqld.

Persistent connections are available only through a PHP module that is integrated into a web server. See Chapter 11 for details.

Example

<?php
  $query = "SELECT * FROM presents";
  
  $connection = mysql_pconnect("localhost", "fred", "shhh");
  mysql_select_db("wedding", $connection);
  
  $result = mysql_query($query, $connection);
  
  while ($row = mysql_fetch_array($result))
     echo $row["present"] . "\n";
  
?>


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.