SlideShare a Scribd company logo
1 of 250
Download to read offline
MySQL and PHP
MySQL and PHP Reference
Abstract

This manual describes the PHP extensions and interfacs that can be used with MySQL.

Document generated on: 2010-04-19 (revision: 20085)
Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved.

This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intel-
lectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast,
modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or
decompilation of this software, unless required by law for interoperability, is prohibited.

The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us
in writing.

If this software or related documentation is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following no-
tice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers
are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific sup-
plemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set
forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR
52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065.

This software is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently
dangerous applications, including applications which may create a risk of personal injury. If you use this software in dangerous applications, then you
shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of this software. Oracle Corporation
and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. MySQL is a trademark of Oracle Corporation and/or its affiliates, and shall
not be used without Oracle's express written authorization. Other names may be trademarks of their respective owners.

This software and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its
affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Cor-
poration and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or
services.

This document in any form, software or printed matter, contains proprietary information that is the exclusive property of Oracle. Your access to and use
of this material is subject to the terms and conditions of your Oracle Software License and Service Agreement, which has been executed and with which
you agree to comply. This document and information contained herein may not be disclosed, copied, reproduced, or distributed to anyone outside Oracle
without prior written consent of Oracle or as specifically provided below. This document is not part of your license agreement nor can it be incorporated
into any contractual agreement with Oracle or its subsidiaries or affiliates.

This documentation is NOT distributed under a GPL license. Use of this documentation is subject to the following terms:

You may create a printed copy of this documentation solely for your own personal use. Conversion to other formats is allowed as long as the actual con-
tent is not altered or edited in any way. You shall not publish or distribute this documentation in any form or on any media, except if you distribute the
documentation in a manner similar to how Oracle disseminates it (that is, electronically for download on a Web site with the software) or on a CD-ROM
or similar medium, provided however that the documentation is disseminated together with the software on the same medium. Any other use, such as any
dissemination of printed copies or use of this documentation, in whole or in part, in another publication, requires the prior written consent from an au-
thorized representative of Oracle. Oracle and/or its affiliates reserve any and all rights to this documentation not expressly granted above.

For more information on the terms of this license, for details on how the MySQL documentation is built and produced, or if you are interested in doing a
translation, please visit http://www.mysql.com/company/contact/.

For additional licensing information, including licenses for libraries used by MySQL, see Preface, Notes, Licenses.

If you want help with using MySQL, please visit either the MySQL Forums or MySQL Mailing Lists where you can discuss your issues with other
MySQL users.

For additional documentation on MySQL products, including translations of the documentation into other languages, and downloadable versions in vari-
ety of formats, including HTML and PDF formats, see the MySQL Documentation Library.
Preface
     PHP is a server-side, HTML-embedded scripting language that may be used to create dynamic Web pages. It is available for most oper-
     ating systems and Web servers, and can access most common databases, including MySQL. PHP may be run as a separate program or
     compiled as a module for use with the Apache Web server.

     PHP actually provides two different MySQL API extensions:


     •   mysql: Available for PHP versions 4 and 5, this extension is intended for use with MySQL versions prior to MySQL 4.1. This ex-
         tension does not support the improved authentication protocol used in MySQL 4.1, nor does it support prepared statements or mul-
         tiple statements. If you wish to use this extension with MySQL 4.1, you will likely want to configure the MySQL server to use the -
         -old-passwords option (see Client does not support authentication protocol). This extension is docu-
         mented on the PHP Web site at http://php.net/mysql.

     •   Chapter 2, MySQL Improved Extension (Mysqli) - Stands for “MySQL, Improved”; this extension is available only in PHP 5. It is
         intended for use with MySQL 4.1.1 and later. This extension fully supports the authentication protocol used in MySQL 5.0, as well
         as the Prepared Statements and Multiple Statements APIs. In addition, this extension provides an advanced, object-oriented pro-
         gramming interface. You can read the documentation for the mysqli extension at http://php.net/mysqli. Helpful article can be
         found at http://devzone.zend.com/node/view/id/686 and http://devzone.zend.com/node/view/id/687.


     If you're experiencing problems with enabling both the mysql and the mysqli extension when building PHP on Linux yourself, see
     Chapter 7, Enabling Both mysql and mysqli in PHP.

     The PHP distribution and documentation are available from the PHP Web site.

             Preface
             MySQL Enterprise subscribers will find more information about MySQL and PHP in the Knowledge Base art-
             icles found at PHP. Access to the MySQL Knowledge Base collection of articles is one of the advantages of
             subscribing to MySQL Enterprise. For more information, see ht-
             tp://www.mysql.com/products/enterprise/knowledgebase.html.

     Portions of this section are Copyright (c) 1997-2008 the PHP Documentation Group This material may be distributed only subject to
     the terms and conditions set forth in the Creative Commons Attribution 3.0 License or later. A copy of the Creative Commons Attribu-
     tion 3.0 license is distributed with this manual. The latest version is presently available at This material may be distributed only subject
     to the terms and conditio ns set forth in the Open Publication License, v1.0.8 or later (the latest version is presently available at ht-
     tp://www.opencontent.org/openpub/).




                                                                   iv
Chapter 1. MySQL Extension (mysql)
         Copyright 1997-2008 the PHP Documentation Group.

         These functions allow you to access MySQL database servers. More information about MySQL can be found at ht-
         tp://www.mysql.com/.

         Documentation for MySQL can be found at http://dev.mysql.com/doc/.

         For an overview of MySQL database connectivity terms and products see Section 2.2, “Overview”.

1.1. Installing/Configuring
         Copyright 1997-2008 the PHP Documentation Group.

1.1.1. Requirements
         Copyright 1997-2008 the PHP Documentation Group.

         In order to have these functions available, you must compile PHP with MySQL support.

1.1.2. Installation
         Copyright 1997-2008 the PHP Documentation Group.

         For compiling, simply use the --with-mysql[=DIR] configuration option where the optional [DIR] points to the MySQL installa-
         tion directory.

         Although this MySQL extension is compatible with MySQL 4.1.0 and greater, it doesn't support the extra functionality that these ver-
         sions provide. For that, use the MySQLi extension.

         If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any
         conflicts.

1.1.2.1. Installation on Linux Systems
         Copyright 1997-2008 the PHP Documentation Group.

1.1.2.1.1. PHP 4
         Copyright 1997-2008 the PHP Documentation Group.

         The option --with-mysql is enabled by default. This default behavior may be disabled with the --without-mysql configure op-
         tion. If MySQL is enabled without specifying the path to the MySQL install DIR, PHP will use the bundled MySQL client libraries.

         Users who run other applications that use MySQL (for example, auth-mysql) should not use the bundled library, but rather specify
         the path to MySQL's install directory, like so: --with-mysql=/path/to/mysql. This will force PHP to use the client libraries in-
         stalled by MySQL, thus avoiding any conflicts.

1.1.2.1.2. PHP 5+
         Copyright 1997-2008 the PHP Documentation Group.

         MySQL is not enabled by default, nor is the MySQL library bundled with PHP. Read this FAQ for details on why. Use the -
         -with-mysql[=DIR] configure option to include MySQL support. You can download headers and libraries from ht-
         tp://www.mysql.com/.

1.1.2.2. Installation on Windows Systems
         Copyright 1997-2008 the PHP Documentation Group.

1.1.2.2.1. PHP 4

                                                                      1
MySQL Extension (mysql)




         Copyright 1997-2008 the PHP Documentation Group.

         The PHP MySQL extension is compiled into PHP.

1.1.2.2.2. PHP 5+
         Copyright 1997-2008 the PHP Documentation Group.

         MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access
         to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk
         to MySQL this file needs to be available to the Windows systems PATH. See the FAQ titled "How do I add my PHP directory to the
         PATH on Windows" for information on how to do this. Although copying libmysql.dll to the Windows system directory also
         works (because the system directory is by default in the system's PATH), it's not recommended.

         As with enabling any PHP extension (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where
         the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is
         c:phpext

                 Note
                 If when starting the web server an error similar to the following occurs: "Unable to load dynamic library
                 './php_mysql.dll'", this is because php_mysql.dll and/or libmysql.dll cannot be found by the system.

1.1.2.3. MySQL Installation Notes
         Copyright 1997-2008 the PHP Documentation Group.

                 Warning
                 Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode ex-
                 tension. See the recode extension for more information.

                 Note
                 If you need charsets other than latin (default), you have to install external (not bundled) libmysql with compiled charset
                 support.

1.1.3. Runtime Configuration
         Copyright 1997-2008 the PHP Documentation Group.

         The behaviour of these functions is affected by settings in php.ini.


         Table 1.1. MySQL Configuration Options
         Name                              Default                            Changeable                         Changelog
         mysql.allow_persistent            "1"                                PHP_INI_SYSTEM
         mysql.max_persistent              "-1"                               PHP_INI_SYSTEM
         mysql.max_links                   "-1"                               PHP_INI_SYSTEM
         mysql.trace_mode                  "0"                                PHP_INI_ALL                        Available since PHP 4.3.0.
         mysql.default_port                NULL                               PHP_INI_ALL
         mysql.default_socket              NULL                               PHP_INI_ALL                        Available since PHP 4.0.1.
         mysql.default_host                NULL                               PHP_INI_ALL
         mysql.default_user                NULL                               PHP_INI_ALL
         mysql.default_password            NULL                               PHP_INI_ALL
         mysql.connect_timeout             "60"                               PHP_INI_ALL                        PHP_INI_SYSTEM in PHP <=
                                                                                                                 4.3.2. Available since PHP
                                                                                                                 4.3.0.


                                                                      2
MySQL Extension (mysql)



      For further details and definitions of the PHP_INI_* modes, see the configuration.changes.modes.

      Here's a short explanation of the configuration directives.



      mysql.allow_persistent                 Whether to allow persistent connections to MySQL.
      boolean
      mysql.max_persistent in-               The maximum number of persistent MySQL connections per process.
      teger
      mysql.max_links integer                The maximum number of MySQL connections per process, including persistent connections.

      mysql.trace_mode boolean               Trace mode. When mysql.trace_mode is enabled, warnings for table/index scans, non free
                                             result sets, and SQL-Errors will be displayed. (Introduced in PHP 4.3.0)

      mysql.default_port string              The default TCP port number to use when connecting to the database server if no other port is
                                             specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT envir-
                                             onment variable, the mysql-tcp entry in /etc/services or the compile-time
                                             MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant.

      mysql.default_socket                   The default socket name to use when connecting to a local database server if no other socket
      string                                 name is specified.

      mysql.default_host string              The default server host to use when connecting to the database server if no other host is specified.
                                             Doesn't apply in SQL safe mode.

      mysql.default_user string              The default user name to use when connecting to the database server if no other name is spe-
                                             cified. Doesn't apply in SQL safe mode.

      mysql.default_password                 The default password to use when connecting to the database server if no other password is spe-
      string                                 cified. Doesn't apply in SQL safe mode.

      mysql.connect_timeout in-              Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer
      teger                                  from the server.


1.1.4. Resource Types
      Copyright 1997-2008 the PHP Documentation Group.

      There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a re-
      source which holds the result of a query.

1.2. Predefined Constants
      Copyright 1997-2008 the PHP Documentation Group.

      The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or
      dynamically loaded at runtime.

      Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect and mysql_pconnect functions. The fol-
      lowing constants are defined:

      Table 1.2. MySQL client constants
       Constant                                                             Description
       MYSQL_CLIENT_COMPRESS                                                Use compression protocol
       MYSQL_CLIENT_IGNORE_SPACE                                            Allow space after function names
       MYSQL_CLIENT_INTERACTIVE                                             Allow interactive_timeout seconds (instead of wait_timeout)
                                                                            of inactivity before closing the connection.
       MYSQL_CLIENT_SSL                                                     Use SSL encryption. This flag is only available with version 4.x of
                                                                            the MySQL client library or newer. Version 3.23.x is bundled both
                                                                            with PHP 4 and Windows binaries of PHP 5.


                                                                    3
MySQL Extension (mysql)




       The function mysql_fetch_array uses a constant for the different types of result arrays. The following constants are defined:

       Table 1.3. MySQL fetch constants
       Constant                                                              Description
       MYSQL_ASSOC                                                           Columns are returned into the array having the fieldname as the ar-
                                                                             ray index.
       MYSQL_BOTH                                                            Columns are returned into the array having both a numerical index
                                                                             and the fieldname as the array index.
       MYSQL_NUM                                                             Columns are returned into the array having a numerical index to
                                                                             the fields. This index starts with 0, the first field in the result.



1.3. Examples
       Copyright 1997-2008 the PHP Documentation Group.

1.3.1. Basic
       This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database.

       Example 1.1. MySQL extension overview example

       Copyright 1997-2008 the PHP Documentation Group.

       <?php
       // Connecting, selecting database
       $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
           or die('Could not connect: ' . mysql_error());
       echo 'Connected successfully';
       mysql_select_db('my_database') or die('Could not select database');
       // Performing SQL query
       $query = 'SELECT * FROM my_table';
       $result = mysql_query($query) or die('Query failed: ' . mysql_error());
       // Printing results in HTML
       echo "<table>n";
       while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
           echo "t<tr>n";
           foreach ($line as $col_value) {
               echo "tt<td>$col_value</td>n";
           }
           echo "t</tr>n";
       }
       echo "</table>n";
       // Free resultset
       mysql_free_result($result);
       // Closing connection
       mysql_close($link);
       ?>




1.4. MySQL Functions
       Copyright 1997-2008 the PHP Documentation Group.

               Note
               Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened con-
               nection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not
               successful, functions return FALSE .

1.4.1. mysql_affected_rows

                                                                     4
MySQL Extension (mysql)




Copyright 1997-2008 the PHP Documentation Group.


•    mysql_affected_rows

     Get number of affected rows in previous MySQL operation


Description
    int mysql_affected_rows(resource link_identifier);


Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier.

Parameters



link_identifier                        The MySQL connection. If the link identifier is not specified, the last link opened by
                                       mysql_connect is assumed. If no such link is found, it will try to create one as if
                                       mysql_connect was called with no arguments. If no connection is found or established, an
                                       E_WARNING level error is generated.


Return Values

Returns the number of affected rows on success, and -1 if the last query failed.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function
will return zero with MySQL versions prior to 4.1.2.

When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility
that mysql_affected_rows may not actually equal the number of rows matched, only the number of rows that were literally af-
fected by the query.

The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the
number of deleted records plus the number of inserted records.

Examples


Example 1.2. mysql_affected_rows example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %dn", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %dn", mysql_affected_rows());
?>




The above example will output something similar to:


Records deleted: 10
Records deleted: 0




                                                              5
MySQL Extension (mysql)




      Example 1.3. mysql_affected_rows example using transactions

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      mysql_select_db('mydb');
      /* Update records */
      mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
      printf ("Updated records: %dn", mysql_affected_rows());
      mysql_query("COMMIT");
      ?>




      The above example will output something similar to:


      Updated Records: 10




      Notes

               Transactions
               If you are using transactions, you need to call mysql_affected_rows after your INSERT, UPDATE, or DELETE
               query, not after the COMMIT.

               SELECT Statements
               To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows.

               Cascaded Foreign Keys
               mysql_affected_rows does not count rows affected implicitly through the use of ON DELETE CASCADE and/or
               ON UPDATE CASCADE in foreign key constraints.

      See Also


      mysql_num_rows
      mysql_info

1.4.2. mysql_client_encoding
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_client_encoding

           Returns the name of the character set


      Description
          string mysql_client_encoding(resource link_identifier);


      Retrieves the character_set variable from MySQL.

      Parameters



                                                               6
MySQL Extension (mysql)




      link_identifier                       The MySQL connection. If the link identifier is not specified, the last link opened by
                                            mysql_connect is assumed. If no such link is found, it will try to create one as if
                                            mysql_connect was called with no arguments. If no connection is found or established, an
                                            E_WARNING level error is generated.


      Return Values

      Returns the default character set name for the current connection.

      Examples


      Example 1.4. mysql_client_encoding example

      <?php
      $link    = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      $charset = mysql_client_encoding($link);
      echo "The current character set is: $charsetn";
      ?>




      The above example will output something similar to:


      The current character set is: latin1




      See Also


      mysql_set_charset
      mysql_real_escape_string

1.4.3. mysql_close
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_close

           Close MySQL connection


      Description
          bool mysql_close(resource link_identifier);


      mysql_close closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If
      link_identifier isn't specified, the last opened link is used.

      Using mysql_close isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
      See also freeing resources.

      Parameters



      link_identifier                       The MySQL connection. If the link identifier is not specified, the last link opened by


                                                                   7
MySQL Extension (mysql)




                                          mysql_connect is assumed. If no such link is found, it will try to create one as if
                                          mysql_connect was called with no arguments. If no connection is found or established, an
                                          E_WARNING level error is generated.


      Return Values

      Returns TRUE on success or FALSE on failure.

      Examples


      Example 1.5. mysql_close example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      echo 'Connected successfully';
      mysql_close($link);
      ?>




      The above example will output:


      Connected successfully




      Notes

               Note
               mysql_close will not close persistent links created by mysql_pconnect.

      See Also


      mysql_connect
      mysql_free_result

1.4.4. mysql_connect
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_connect

           Open a connection to a MySQL Server


      Description
          resource mysql_connect(string server= =ini_get("mysql.default_host"),
                                 string username= =ini_get("mysql.default_user"),
                                 string password= =ini_get("mysql.default_password"),
                                 bool new_link= =false,
                                 int client_flags= =0);


      Opens or reuses a connection to a MySQL server.

      Parameters

                                                               8
MySQL Extension (mysql)




server                              The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local
                                    socket e.g. ":/path/to/socket" for the localhost.

                                    If the PHP directive mysql.default_host is undefined (default), then the default value is 'local-
                                    host:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used.

username                            The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter
                                    is ignored and the name of the user that owns the server process is used.

password                            The password. Default value is defined by mysql.default_password. In SQL safe mode, this para-
                                    meter is ignored and empty password is used.

new_link                            If a second call is made to mysql_connect with the same arguments, no new link will be es-
                                    tablished, but instead, the link identifier of the already opened link will be returned. The
                                    new_link parameter modifies this behavior and makes mysql_connect always open a new
                                    link, even if mysql_connect was called before with the same parameters. In SQL safe mode,
                                    this parameter is ignored.

client_flags                        The client_flags parameter can be a combination of the following constants: 128 (enable
                                    LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL , MYSQL_CLIENT_COMPRESS ,
                                    MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE . Read the section
                                    about Table 1.2, “MySQL client constants” for further information. In SQL safe mode, this para-
                                    meter is ignored.


Return Values

Returns a MySQL link identifier on success or FALSE on failure.

Changelog


Version                                                           Description
4.3.0                                                             Added the client_flags parameter.
4.2.0                                                             Added the new_link parameter.


Examples


Example 1.6. mysql_connect example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>




Example 1.7. mysql_connect example using hostname:port syntax

<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());


                                                          9
MySQL Extension (mysql)



      }
      echo 'Connected successfully';
      mysql_close($link);
      // we connect to localhost at port 3307
      $link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      echo 'Connected successfully';
      mysql_close($link);
      ?>




      Example 1.8. mysql_connect example using ":/path/to/socket" syntax

      <?php
      // we connect to localhost and socket e.g. /tmp/mysql.sock
      //variant 1: ommit localhost
      $link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      echo 'Connected successfully';
      mysql_close($link);
      // variant 2: with localhost
      $link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      echo 'Connected successfully';
      mysql_close($link);
      ?>




      Notes

              Note
              Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to con-
              nect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the
              MySQL client library tries to connect to the wrong local socket, you should set the correct path as
              mysql.default_host string in your PHP configuration and leave the server field blank.

              Note
              The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly call-
              ing mysql_close.

              Note
              You can suppress the error message on failure by prepending a @ to the function name.

              Note
              Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain
              character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and
              PHP will have problems loading Winsock.

      See Also


      mysql_pconnect
      mysql_close

1.4.5. mysql_create_db

                                                                     10
MySQL Extension (mysql)




Copyright 1997-2008 the PHP Documentation Group.


•    mysql_create_db

     Create a MySQL database


Description
    bool mysql_create_db(string database_name,
                         resource link_identifier);


mysql_create_db attempts to create a new database on the server associated with the specified link identifier.

Parameters



database_name                        The name of the database being created.

link_identifier                      The MySQL connection. If the link identifier is not specified, the last link opened by
                                     mysql_connect is assumed. If no such link is found, it will try to create one as if
                                     mysql_connect was called with no arguments. If no connection is found or established, an
                                     E_WARNING level error is generated.


Return Values

Returns TRUE on success or FALSE on failure.

Examples


Example 1.9. mysql_create_db alternative example

The function mysql_create_db is deprecated. It is preferable to use mysql_query to issue a sql CREATE DATABASE statement
instead.

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
    echo "Database my_db created successfullyn";
} else {
    echo 'Error creating database: ' . mysql_error() . "n";
}
?>




The above example will output something similar to:


Database my_db created successfully




Notes

         Note
         For backward compatibility, the following deprecated alias may be used: mysql_createdb

                                                          11
MySQL Extension (mysql)




               Note
               This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

      See Also


      mysql_query
      mysql_select_db

1.4.6. mysql_data_seek
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_data_seek

           Move internal result pointer


      Description
          bool mysql_data_seek(resource result,
                               int row_number);


      mysql_data_seek moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the
      specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc, would return that row.

      row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows - 1. However if the result
      set is empty (mysql_num_rows == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek will return FALSE .

      Parameters



      result                                The result resource that is being evaluated. This result comes from a call to mysql_query.

      row_number                            The desired row number of the new result pointer.


      Return Values

      Returns TRUE on success or FALSE on failure.

      Examples


      Example 1.10. mysql_data_seek example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      $db_selected = mysql_select_db('sample_db');
      if (!$db_selected) {
          die('Could not select database: ' . mysql_error());
      }
      $query = 'SELECT last_name, first_name FROM friends';
      $result = mysql_query($query);
      if (!$result) {
          die('Query failed: ' . mysql_error());
      }
      /* fetch rows in reverse order */
      for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
          if (!mysql_data_seek($result, $i)) {
              echo "Cannot seek to row $i: " . mysql_error() . "n";
              continue;
          }


                                                                  12
MySQL Extension (mysql)



            if (!($row = mysql_fetch_assoc($result))) {
                continue;
            }
            echo $row['last_name'] . ' ' . $row['first_name'] . "<br />n";
      }
      mysql_free_result($result);
      ?>




      Notes

               Note
               The function mysql_data_seek can be used in conjunction only with mysql_query, not with
               mysql_unbuffered_query.

      See Also


      mysql_query
      mysql_num_rows
      mysql_fetch_row
      mysql_fetch_assoc
      mysql_fetch_array
      mysql_fetch_object

1.4.7. mysql_db_name
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_db_name

           Get result data


      Description
          string mysql_db_name(resource result,
                               int row,
                               mixed field);


      Retrieve the database name from a call to mysql_list_dbs.

      Parameters



      result                              The result pointer from a call to mysql_list_dbs.

      row                                 The index into the result set.

      field                               The field name.


      Return Values

      Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error to determine the nature of the
      error.

      Examples


      Example 1.11. mysql_db_name example


                                                                 13
MySQL Extension (mysql)




      <?php
      error_reporting(E_ALL);
      $link = mysql_connect('dbhost', 'username', 'password');
      $db_list = mysql_list_dbs($link);
      $i = 0;
      $cnt = mysql_num_rows($db_list);
      while ($i < $cnt) {
          echo mysql_db_name($db_list, $i) . "n";
          $i++;
      }
      ?>




      Notes

              Note
              For backward compatibility, the following deprecated alias may be used: mysql_dbname

      See Also


      mysql_list_dbs
      mysql_tablename

1.4.8. mysql_db_query
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_db_query

           Send a MySQL query


      Description
          resource mysql_db_query(string database,
                                  string query,
                                  resource link_identifier);


      mysql_db_query selects a database, and executes a query on it.

              Warning
              This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

      Parameters



      database                             The name of the database that will be selected.

      query                                The MySQL query.

                                           Data inside the query should be properly escaped.

      link_identifier                      The MySQL connection. If the link identifier is not specified, the last link opened by
                                           mysql_connect is assumed. If no such link is found, it will try to create one as if
                                           mysql_connect was called with no arguments. If no connection is found or established, an
                                           E_WARNING level error is generated.


      Return Values

      Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE / FALSE for


                                                                 14
MySQL Extension (mysql)



      /UPDATE/DELETE queries to indicate success/failure.

      Changelog


      Version                                                             Description
      5.3.0                                                               This function now throws an E_DEPRECATED notice.
      4.0.6                                                               This function is deprecated, do not use this function. Use
                                                                          mysql_select_db and mysql_query instead.


      Examples


      Example 1.12. mysql_db_query alternative example

      <?php
      if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
           echo 'Could not connect to mysql';
           exit;
      }
      if (!mysql_select_db('mysql_dbname', $link)) {
           echo 'Could not select database';
           exit;
      }
      $sql     = 'SELECT foo FROM bar WHERE id = 42';
      $result = mysql_query($sql, $link);
      if (!$result) {
           echo "DB Error, could not query the databasen";
           echo 'MySQL Error: ' . mysql_error();
           exit;
      }
      while ($row = mysql_fetch_assoc($result)) {
           echo $row['foo'];
      }
      mysql_free_result($result);
      ?>




      Notes

               Note
               Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use
               this function to temporarily run a sql query on another database, you would have to manually switch back. Users are
               strongly encouraged to use the database.table syntax in their sql queries or mysql_select_db instead of this
               function.

      See Also


      mysql_query
      mysql_select_db

1.4.9. mysql_drop_db
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_drop_db

           Drop (delete) a MySQL database


      Description
          bool mysql_drop_db(string database_name,


                                                                  15
MySQL Extension (mysql)



                              resource link_identifier);


      mysql_drop_db attempts to drop (remove) an entire database from the server associated with the specified link identifier. This func-
      tion is deprecated, it is preferable to use mysql_query to issue a sql DROP DATABASE statement instead.

      Parameters



      database_name                        The name of the database that will be deleted.

      link_identifier                      The MySQL connection. If the link identifier is not specified, the last link opened by
                                           mysql_connect is assumed. If no such link is found, it will try to create one as if
                                           mysql_connect was called with no arguments. If no connection is found or established, an
                                           E_WARNING level error is generated.


      Return Values

      Returns TRUE on success or FALSE on failure.

      Examples


      Example 1.13. mysql_drop_db alternative example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      $sql = 'DROP DATABASE my_db';
      if (mysql_query($sql, $link)) {
          echo "Database my_db was successfully droppedn";
      } else {
          echo 'Error dropping database: ' . mysql_error() . "n";
      }
      ?>




      Notes

              Warning
              This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

              Note
              For backward compatibility, the following deprecated alias may be used: mysql_dropdb

      See Also


      mysql_query

1.4.10. mysql_errno
      Copyright 1997-2008 the PHP Documentation Group.


      •   mysql_errno

          Returns the numerical value of the error message from previous MySQL operation



                                                                 16
MySQL Extension (mysql)




      Description
          int mysql_errno(resource link_identifier);


      Returns the error number from the last MySQL function.

      Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno to retrieve the error
      code. Note that this function only returns the error code from the most recently executed MySQL function (not including
      mysql_error and mysql_errno), so if you want to use it, make sure you check the value before calling another MySQL function.

      Parameters



      link_identifier                       The MySQL connection. If the link identifier is not specified, the last link opened by
                                            mysql_connect is assumed. If no such link is found, it will try to create one as if
                                            mysql_connect was called with no arguments. If no connection is found or established, an
                                            E_WARNING level error is generated.


      Return Values

      Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.

      Examples


      Example 1.14. mysql_errno example

      <?php
      $link = mysql_connect("localhost", "mysql_user", "mysql_password");
      if (!mysql_select_db("nonexistentdb", $link)) {
          echo mysql_errno($link) . ": " . mysql_error($link). "n";
      }
      mysql_select_db("kossu", $link);
      if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
          echo mysql_errno($link) . ": " . mysql_error($link) . "n";
      }
      ?>




      The above example will output something similar to:


      1049: Unknown database 'nonexistentdb'
      1146: Table 'kossu.nonexistenttable' doesn't exist




      See Also


      mysql_error
      MySQL error codes

1.4.11. mysql_error
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_error

           Returns the text of the error message from previous MySQL operation


                                                                 17
MySQL Extension (mysql)




      Description
          string mysql_error(resource link_identifier);


      Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings.
      Instead, use mysql_error to retrieve the error text. Note that this function only returns the error text from the most recently executed
      MySQL function (not including mysql_error and mysql_errno), so if you want to use it, make sure you check the value before
      calling another MySQL function.

      Parameters



      link_identifier                        The MySQL connection. If the link identifier is not specified, the last link opened by
                                             mysql_connect is assumed. If no such link is found, it will try to create one as if
                                             mysql_connect was called with no arguments. If no connection is found or established, an
                                             E_WARNING level error is generated.


      Return Values

      Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.

      Examples


      Example 1.15. mysql_error example

      <?php
      $link = mysql_connect("localhost", "mysql_user", "mysql_password");
      mysql_select_db("nonexistentdb", $link);
      echo mysql_errno($link) . ": " . mysql_error($link). "n";
      mysql_select_db("kossu", $link);
      mysql_query("SELECT * FROM nonexistenttable", $link);
      echo mysql_errno($link) . ": " . mysql_error($link) . "n";
      ?>




      The above example will output something similar to:


      1049: Unknown database 'nonexistentdb'
      1146: Table 'kossu.nonexistenttable' doesn't exist




      See Also


      mysql_errno
      MySQL error codes

1.4.12. mysql_escape_string
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_escape_string

           Escapes a string for use in a mysql_query


      Description


                                                                  18
MySQL Extension (mysql)



  string mysql_escape_string(string unescaped_string);


This function will escape the unescaped_string, so that it is safe to place it in a mysql_query. This function is deprecated.

This function is identical to mysql_real_escape_string except that mysql_real_escape_string takes a connection
handler and escapes the string according to the current character set. mysql_escape_string does not take a connection argument
and does not respect the current charset setting.

        Warning
        This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Parameters



unescaped_string                    The string that is to be escaped.


Return Values

Returns the escaped string.

Changelog


Version                                                            Description
5.3.0                                                              This function now throws an E_DEPRECATED notice.
4.3.0                                                              This function became deprecated, do not use this function. Instead,
                                                                   use mysql_real_escape_string.


Examples


Example 1.16. mysql_escape_string example

<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %sn", $escaped_item);
?>




The above example will output:


Escaped string: Zak's Laptop




Notes

        Note
        mysql_escape_string does not escape % and _.

See Also


mysql_real_escape_string


                                                          19
MySQL Extension (mysql)



      addslashes
      The magic_quotes_gpc directive.

1.4.13. mysql_fetch_array
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_fetch_array

           Fetch a result row as an associative array, a numeric array, or both


      Description
          array mysql_fetch_array(resource result,
                                  int result_type= =MYSQL_BOTH);


      Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

      Parameters



      result                                  The result resource that is being evaluated. This result comes from a call to mysql_query.

      result_type                             The type of array that is to be fetched. It's a constant and can take the following values:
                                              MYSQL_ASSOC , MYSQL_NUM , and MYSQL_BOTH .


      Return Values

      Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends
      on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Us-
      ing MYSQL_ASSOC , you only get associative indices (as mysql_fetch_assoc works), using MYSQL_NUM , you only get number
      indices (as mysql_fetch_row works).

      If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of
      the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access
      the contents with the original column name.

      Examples


      Example 1.17. Query with aliased duplicate field names

      SELECT table1.field AS foo, table2.field AS bar FROM table1, table2




      Example 1.18. mysql_fetch_array with MYSQL_NUM

      <?php
      mysql_connect("localhost", "mysql_user", "mysql_password") or
          die("Could not connect: " . mysql_error());
      mysql_select_db("mydb");
      $result = mysql_query("SELECT id, name FROM mytable");
      while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
          printf("ID: %s Name: %s", $row[0], $row[1]);
      }
      mysql_free_result($result);
      ?>




                                                                     20
MySQL Extension (mysql)




      Example 1.19. mysql_fetch_array with MYSQL_ASSOC

      <?php
      mysql_connect("localhost", "mysql_user", "mysql_password") or
          die("Could not connect: " . mysql_error());
      mysql_select_db("mydb");
      $result = mysql_query("SELECT id, name FROM mytable");
      while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
          printf("ID: %s Name: %s", $row["id"], $row["name"]);
      }
      mysql_free_result($result);
      ?>




      Example 1.20. mysql_fetch_array with MYSQL_BOTH

      <?php
      mysql_connect("localhost", "mysql_user", "mysql_password") or
          die("Could not connect: " . mysql_error());
      mysql_select_db("mydb");
      $result = mysql_query("SELECT id, name FROM mytable");
      while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
          printf ("ID: %s Name: %s", $row[0], $row["name"]);
      }
      mysql_free_result($result);
      ?>




      Notes

              Performance
              An important thing to note is that using mysql_fetch_array is not significantly slower than using
              mysql_fetch_row, while it provides a significant added value.

              Note
              Field names returned by this function are case-sensitive.

              Note
              This function sets NULL fields to the PHP NULL value.

      See Also


      mysql_fetch_row
      mysql_fetch_assoc
      mysql_data_seek
      mysql_query

1.4.14. mysql_fetch_assoc
      Copyright 1997-2008 the PHP Documentation Group.


      •   mysql_fetch_assoc

          Fetch a result row as an associative array



                                                                  21
MySQL Extension (mysql)




Description
  array mysql_fetch_assoc(resource result);


Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc is
equivalent to calling mysql_fetch_array with MYSQL_ASSOC for the optional second parameter. It only returns an associative
array.

Parameters



result                                The result resource that is being evaluated. This result comes from a call to mysql_query.


Return Values

Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of
the same name, you either need to access the result with numeric indices by using mysql_fetch_row or add alias names. See the ex-
ample at the mysql_fetch_array description about aliases.

Examples


Example 1.21. An expanded mysql_fetch_assoc example

<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}
if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}
$sql = "SELECT id as userid, fullname, userstatus
        FROM    sometable
        WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}
if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//        then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}
mysql_free_result($result);
?>




Notes

        Performance
        An important thing to note is that using mysql_fetch_assoc is not significantly slower than using
        mysql_fetch_row, while it provides a significant added value.


                                                            22
MySQL Extension (mysql)




               Note
               Field names returned by this function are case-sensitive.

               Note
               This function sets NULL fields to the PHP NULL value.

      See Also


      mysql_fetch_row
      mysql_fetch_array
      mysql_data_seek
      mysql_query
      mysql_error

1.4.15. mysql_fetch_field
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_fetch_field

           Get column information from a result and return as an object


      Description
          object mysql_fetch_field(resource result,
                                   int field_offset= =0);


      Returns an object containing field information. This function can be used to obtain information about fields in the provided query result.

      Parameters



      result                                   The result resource that is being evaluated. This result comes from a call to mysql_query.

      field_offset                             The numerical field offset. If the field offset is not specified, the next field that was not yet re-
                                               trieved by this function is retrieved. The field_offset starts at 0.


      Return Values

      Returns an object containing field information. The properties of the object are:



      •    name - column name

      •    table - name of the table the column belongs to

      •    def - default value of the column

      •    max_length - maximum length of the column

      •    not_null - 1 if the column cannot be NULL

      •    primary_key - 1 if the column is a primary key

      •    unique_key - 1 if the column is a unique key

      •    multiple_key - 1 if the column is a non-unique key



                                                                      23
MySQL Extension (mysql)




      •   numeric - 1 if the column is numeric

      •   blob - 1 if the column is a BLOB

      •   type - the type of the column

      •   unsigned - 1 if the column is unsigned

      •   zerofill - 1 if the column is zero-filled


      Examples


      Example 1.22. mysql_fetch_field example

      <?php
      $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$conn) {
          die('Could not connect: ' . mysql_error());
      }
      mysql_select_db('database');
      $result = mysql_query('select * from table');
      if (!$result) {
          die('Query failed: ' . mysql_error());
      }
      /* get column metadata */
      $i = 0;
      while ($i < mysql_num_fields($result)) {
          echo "Information for column $i:<br />n";
          $meta = mysql_fetch_field($result, $i);
          if (!$meta) {
               echo "No information available<br />n";
          }
          echo "<pre>
      blob:          $meta->blob
      max_length:    $meta->max_length
      multiple_key: $meta->multiple_key
      name:          $meta->name
      not_null:      $meta->not_null
      numeric:       $meta->numeric
      primary_key: $meta->primary_key
      table:         $meta->table
      type:          $meta->type
      default:       $meta->def
      unique_key:    $meta->unique_key
      unsigned:      $meta->unsigned
      zerofill:      $meta->zerofill
      </pre>";
          $i++;
      }
      mysql_free_result($result);
      ?>




      Notes

               Note
               Field names returned by this function are case-sensitive.

      See Also


      mysql_field_seek

1.4.16. mysql_fetch_lengths
      Copyright 1997-2008 the PHP Documentation Group.




                                                                   24
MySQL Extension (mysql)




•    mysql_fetch_lengths

     Get the length of each output in a result


Description
    array mysql_fetch_lengths(resource result);


Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL.

mysql_fetch_lengths stores the lengths of each result column in the last row returned by mysql_fetch_row,
mysql_fetch_assoc, mysql_fetch_array, and mysql_fetch_object in an array, starting at offset 0.

Parameters



result                                  The result resource that is being evaluated. This result comes from a call to mysql_query.


Return Values

An array of lengths on success or FALSE on failure.

Examples


Example 1.23. A mysql_fetch_lengths example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
     echo 'Could not run query: ' . mysql_error();
     exit;
}
$row       = mysql_fetch_assoc($result);
$lengths = mysql_fetch_lengths($result);
print_r($row);
print_r($lengths);
?>




The above example will output something similar to:


Array
(
    [id] => 42
    [email] => user@example.com
)
Array
(
    [0] => 2
    [1] => 16
)




See Also


mysql_field_len
mysql_fetch_row
strlen



                                                             25
MySQL Extension (mysql)



1.4.17. mysql_fetch_object
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_fetch_object

           Fetch a result row as an object


      Description
          object mysql_fetch_object(resource result,
                                    string class_name,
                                    array params);


      Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

      Parameters



      result                                 The result resource that is being evaluated. This result comes from a call to mysql_query.

      class_name                             The name of the class to instantiate, set the properties of and return. If not specified, a
                                             stdClass object is returned.

      params                                 An optional array of parameters to pass to the constructor for class_name objects.


      Return Values

      Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows.

      Changelog


      Version                                                                Description
      5.0.0                                                                  Added the ability to return as a different object.


      Examples


      Example 1.24. mysql_fetch_object example

      <?php
      mysql_connect("hostname", "user", "password");
      mysql_select_db("mydb");
      $result = mysql_query("select * from mytable");
      while ($row = mysql_fetch_object($result)) {
          echo $row->user_id;
          echo $row->fullname;
      }
      mysql_free_result($result);
      ?>




      Example 1.25. mysql_fetch_object example

      <?php
      class foo {
          public $name;


                                                                    26
MySQL Extension (mysql)



      }
      mysql_connect("hostname", "user", "password");
      mysql_select_db("mydb");
      $result = mysql_query("select name from mytable limit 1");
      $obj = mysql_fetch_object($result, 'foo');
      var_dump($obj);
      ?>




      Notes

               Performance
               Speed-wise, the function is identical to mysql_fetch_array, and almost as quick as mysql_fetch_row (the dif-
               ference is insignificant).

               Note
               mysql_fetch_object is similar to mysql_fetch_array, with one difference - an object is returned, instead of an
               array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are il-
               legal property names).

               Note
               Field names returned by this function are case-sensitive.

               Note
               This function sets NULL fields to the PHP NULL value.

      See Also


      mysql_fetch_array
      mysql_fetch_assoc
      mysql_fetch_row
      mysql_data_seek
      mysql_query

1.4.18. mysql_fetch_row
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_fetch_row

           Get a result row as an enumerated array


      Description
          array mysql_fetch_row(resource result);


      Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.

      Parameters



      result                                 The result resource that is being evaluated. This result comes from a call to mysql_query.


      Return Values

      Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

                                                                    27
MySQL Extension (mysql)




      mysql_fetch_row fetches one row of data from the result associated with the specified result identifier. The row is returned as an
      array. Each result column is stored in an array offset, starting at offset 0.

      Examples


      Example 1.26. Fetching one row with mysql_fetch_row

      <?php
      $result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
      if (!$result) {
          echo 'Could not run query: ' . mysql_error();
          exit;
      }
      $row = mysql_fetch_row($result);
      echo $row[0]; // 42
      echo $row[1]; // the email value
      ?>




      Notes

               Note
               This function sets NULL fields to the PHP NULL value.

      See Also


      mysql_fetch_array
      mysql_fetch_assoc
      mysql_fetch_object
      mysql_data_seek
      mysql_fetch_lengths
      mysql_result

1.4.19. mysql_field_flags
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_field_flags

           Get the flags associated with the specified field in a result


      Description
          string mysql_field_flags(resource result,
                                   int field_offset);


      mysql_field_flags returns the field flags of the specified field. The flags are reported as a single word per flag separated by a
      single space, so that you can split the returned value using explode.

      Parameters



      result                                   The result resource that is being evaluated. This result comes from a call to mysql_query.

      field_offset                             The numerical field offset. The field_offset starts at 0. If field_offset does not exist,
                                               an error of level E_WARNING is also issued.




                                                                      28
MySQL Extension (mysql)




      Return Values

      Returns a string of flags associated with the result or FALSE on failure.

      The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key",
      "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and
      "timestamp".

      Examples


      Example 1.27. A mysql_field_flags example

      <?php
      $result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
      if (!$result) {
          echo 'Could not run query: ' . mysql_error();
          exit;
      }
      $flags = mysql_field_flags($result, 0);
      echo $flags;
      print_r(explode(' ', $flags));
      ?>




      The above example will output something similar to:


      not_null primary_key auto_increment
      Array
      (
          [0] => not_null
          [1] => primary_key
          [2] => auto_increment
      )




      Notes

               Note
               For backward compatibility, the following deprecated alias may be used: mysql_fieldflags

      See Also


      mysql_field_type
      mysql_field_len

1.4.20. mysql_field_len
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_field_len

           Returns the length of the specified field


      Description
          int mysql_field_len(resource result,
                              int field_offset);




                                                                   29
MySQL Extension (mysql)




      mysql_field_len returns the length of the specified field.

      Parameters



      result                                   The result resource that is being evaluated. This result comes from a call to mysql_query.

      field_offset                             The numerical field offset. The field_offset starts at 0. If field_offset does not exist,
                                               an error of level E_WARNING is also issued.


      Return Values

      The length of the specified field index on success or FALSE on failure.

      Examples


      Example 1.28. mysql_field_len example

      <?php
      $result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
      if (!$result) {
          echo 'Could not run query: ' . mysql_error();
          exit;
      }
      // Will get the length of the id field as specified in the database
      // schema.
      $length = mysql_field_len($result, 0);
      echo $length;
      ?>




      Notes

               Note
               For backward compatibility, the following deprecated alias may be used: mysql_fieldlen

      See Also


      mysql_fetch_lengths
      strlen

1.4.21. mysql_field_name
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_field_name

           Get the name of the specified field in a result


      Description
          string mysql_field_name(resource result,
                                  int field_offset);


      mysql_field_name returns the name of the specified field index.

      Parameters


                                                                    30
MySQL Extension (mysql)




      result                                The result resource that is being evaluated. This result comes from a call to mysql_query.

      field_offset                          The numerical field offset. The field_offset starts at 0. If field_offset does not exist,
                                            an error of level E_WARNING is also issued.


      Return Values

      The name of the specified field index on success or FALSE on failure.

      Examples


      Example 1.29. mysql_field_name example

      <?php
      /* The users table consists of three fields:
      *   user_id
      *   username
      *   password.
      */
      $link = @mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect to MySQL server: ' . mysql_error());
      }
      $dbname = 'mydb';
      $db_selected = mysql_select_db($dbname, $link);
      if (!$db_selected) {
          die("Could not set $dbname: " . mysql_error());
      }
      $res = mysql_query('select * from users', $link);
      echo mysql_field_name($res, 0) . "n";
      echo mysql_field_name($res, 2);
      ?>




      The above example will output:


      user_id
      password




      Notes

              Note
              Field names returned by this function are case-sensitive.

              Note
              For backward compatibility, the following deprecated alias may be used: mysql_fieldname

      See Also


      mysql_field_type
      mysql_field_len

1.4.22. mysql_field_seek
      Copyright 1997-2008 the PHP Documentation Group.



                                                                  31
MySQL Extension (mysql)




      •    mysql_field_seek

           Set result pointer to a specified field offset


      Description
          bool mysql_field_seek(resource result,
                                int field_offset);


      Seeks to the specified field offset. If the next call to mysql_fetch_field doesn't include a field offset, the field offset specified in
      mysql_field_seek will be returned.

      Parameters



      result                                    The result resource that is being evaluated. This result comes from a call to mysql_query.

      field_offset                              The numerical field offset. The field_offset starts at 0. If field_offset does not exist,
                                                an error of level E_WARNING is also issued.


      Return Values

      Returns TRUE on success or FALSE on failure.

      See Also


      mysql_fetch_field

1.4.23. mysql_field_table
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_field_table

           Get name of the table the specified field is in


      Description
          string mysql_field_table(resource result,
                                   int field_offset);


      Returns the name of the table that the specified field is in.

      Parameters



      result                                    The result resource that is being evaluated. This result comes from a call to mysql_query.

      field_offset                              The numerical field offset. The field_offset starts at 0. If field_offset does not exist,
                                                an error of level E_WARNING is also issued.


      Return Values

      The name of the table on success.

      Examples




                                                                      32
MySQL Extension (mysql)




      Example 1.30. A mysql_field_table example

      <?php
      $query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = countr
      // get the result from the DB
      $result = mysql_query($query);
      // Lists the table name and then the field name
      for ($i = 0; $i < mysql_num_fields($result); ++$i) {
          $table = mysql_field_table($result, $i);
          $field = mysql_field_name($result, $i);
          echo "$table: $fieldn";
      }
      ?>




      Notes

               Note
               For backward compatibility, the following deprecated alias may be used: mysql_fieldtable

      See Also


      mysql_list_tables

1.4.24. mysql_field_type
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_field_type

           Get the type of the specified field in a result


      Description
          string mysql_field_type(resource result,
                                  int field_offset);


      mysql_field_type is similar to the mysql_field_name function. The arguments are identical, but the field type is returned in-
      stead.

      Parameters



      result                                    The result resource that is being evaluated. This result comes from a call to mysql_query.

      field_offset                              The numerical field offset. The field_offset starts at 0. If field_offset does not exist,
                                                an error of level E_WARNING is also issued.


      Return Values

      The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the MySQL documentation.

      Examples


      Example 1.31. mysql_field_type example



                                                                       33
MySQL Extension (mysql)



      <?php
      mysql_connect("localhost", "mysql_username", "mysql_password");
      mysql_select_db("mysql");
      $result = mysql_query("SELECT * FROM func");
      $fields = mysql_num_fields($result);
      $rows    = mysql_num_rows($result);
      $table = mysql_field_table($result, 0);
      echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)n";
      echo "The table has the following fields:n";
      for ($i=0; $i < $fields; $i++) {
          $type = mysql_field_type($result, $i);
          $name = mysql_field_name($result, $i);
          $len    = mysql_field_len($result, $i);
          $flags = mysql_field_flags($result, $i);
          echo $type . " " . $name . " " . $len . " " . $flags . "n";
      }
      mysql_free_result($result);
      mysql_close();
      ?>




      The above example will output something similar to:


      Your 'func' table has 4 fields and 1 record(s)
      The table has the following fields:
      string name 64 not_null primary_key binary
      int ret 1 not_null
      string dl 128 not_null
      string type 9 not_null enum




      Notes

               Note
               For backward compatibility, the following deprecated alias may be used: mysql_fieldtype

      See Also


      mysql_field_name
      mysql_field_len

1.4.25. mysql_free_result
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_free_result

           Free result memory


      Description
          bool mysql_free_result(resource result);


      mysql_free_result will free all memory associated with the result identifier result.

      mysql_free_result only needs to be called if you are concerned about how much memory is being used for queries that return
      large result sets. All associated result memory is automatically freed at the end of the script's execution.

      Parameters



      result                               The result resource that is being evaluated. This result comes from a call to mysql_query.


                                                                34
MySQL Extension (mysql)




      Return Values

      Returns TRUE on success or FALSE on failure.

      If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query only
      returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

      Examples


      Example 1.32. A mysql_free_result example

      <?php
      $result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
      if (!$result) {
          echo 'Could not run query: ' . mysql_error();
          exit;
      }
      /* Use the result, assuming we're done with it afterwards */
      $row = mysql_fetch_assoc($result);
      /* Now we free up the result and continue on with our script */
      mysql_free_result($result);
      echo $row['id'];
      echo $row['email'];
      ?>




      Notes

               Note
               For backward compatibility, the following deprecated alias may be used: mysql_freeresult

      See Also


      mysql_query
      is_resource

1.4.26. mysql_get_client_info
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_get_client_info

           Get MySQL client info


      Description
          string mysql_get_client_info();


      mysql_get_client_info returns a string that represents the client library version.

      Return Values

      The MySQL client version.

      Examples


      Example 1.33. mysql_get_client_info example


                                                               35
MySQL Extension (mysql)




      <?php
      printf("MySQL client info: %sn", mysql_get_client_info());
      ?>




      The above example will output something similar to:


      MySQL client info: 3.23.39




      See Also


      mysql_get_host_info
      mysql_get_proto_info
      mysql_get_server_info

1.4.27. mysql_get_host_info
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_get_host_info

           Get MySQL host info


      Description
          string mysql_get_host_info(resource link_identifier);


      Describes the type of connection in use for the connection, including the server host name.

      Parameters



      link_identifier                       The MySQL connection. If the link identifier is not specified, the last link opened by
                                            mysql_connect is assumed. If no such link is found, it will try to create one as if
                                            mysql_connect was called with no arguments. If no connection is found or established, an
                                            E_WARNING level error is generated.


      Return Values

      Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure.

      Examples


      Example 1.34. mysql_get_host_info example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      printf("MySQL host info: %sn", mysql_get_host_info());
      ?>




                                                                  36
MySQL Extension (mysql)




      The above example will output something similar to:


      MySQL host info: Localhost via UNIX socket




      See Also


      mysql_get_client_info
      mysql_get_proto_info
      mysql_get_server_info

1.4.28. mysql_get_proto_info
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_get_proto_info

           Get MySQL protocol info


      Description
          int mysql_get_proto_info(resource link_identifier);


      Retrieves the MySQL protocol.

      Parameters



      link_identifier                      The MySQL connection. If the link identifier is not specified, the last link opened by
                                           mysql_connect is assumed. If no such link is found, it will try to create one as if
                                           mysql_connect was called with no arguments. If no connection is found or established, an
                                           E_WARNING level error is generated.


      Return Values

      Returns the MySQL protocol on success or FALSE on failure.

      Examples


      Example 1.35. mysql_get_proto_info example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      printf("MySQL protocol version: %sn", mysql_get_proto_info());
      ?>




      The above example will output something similar to:


      MySQL protocol version: 10



                                                               37
MySQL Extension (mysql)




      See Also


      mysql_get_client_info
      mysql_get_host_info
      mysql_get_server_info

1.4.29. mysql_get_server_info
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_get_server_info

           Get MySQL server info


      Description
          string mysql_get_server_info(resource link_identifier);


      Retrieves the MySQL server version.

      Parameters



      link_identifier                       The MySQL connection. If the link identifier is not specified, the last link opened by
                                            mysql_connect is assumed. If no such link is found, it will try to create one as if
                                            mysql_connect was called with no arguments. If no connection is found or established, an
                                            E_WARNING level error is generated.


      Return Values

      Returns the MySQL server version on success or FALSE on failure.

      Examples


      Example 1.36. mysql_get_server_info example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      printf("MySQL server version: %sn", mysql_get_server_info());
      ?>




      The above example will output something similar to:


      MySQL server version: 4.0.1-alpha




      See Also


                                                                38
MySQL Extension (mysql)




      mysql_get_client_info
      mysql_get_host_info
      mysql_get_proto_info
      phpversion

1.4.30. mysql_info
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_info

           Get information about the most recent query


      Description
          string mysql_info(resource link_identifier);


      Returns detailed information about the last query.

      Parameters



      link_identifier                        The MySQL connection. If the link identifier is not specified, the last link opened by
                                             mysql_connect is assumed. If no such link is found, it will try to create one as if
                                             mysql_connect was called with no arguments. If no connection is found or established, an
                                             E_WARNING level error is generated.


      Return Values

      Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide inform-
      ation, and what the returned value may look like. Statements that are not listed will return FALSE .

      Examples


      Example 1.37. Relevant MySQL Statements

      Statements that return string values. The numbers are only for illustrating purpose; their values will correspond to the query.

      INSERT INTO ... SELECT ...
      String format: Records: 23 Duplicates: 0 Warnings: 0
      INSERT INTO ... VALUES (...),(...),(...)...
      String format: Records: 37 Duplicates: 0 Warnings: 0
      LOAD DATA INFILE ...
      String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0
      ALTER TABLE
      String format: Records: 60 Duplicates: 0 Warnings: 0
      UPDATE
      String format: Rows matched: 65 Changed: 65 Warnings: 0




      Notes

               Note
               mysql_info returns a non- FALSE value for the INSERT ... VALUES statement only if multiple value lists are spe-
               cified in the statement.

      See Also

                                                                   39
MySQL Extension (mysql)




      mysql_affected_rows
      mysql_insert_id
      mysql_stat

1.4.31. mysql_insert_id
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_insert_id

           Get the ID generated in the last query


      Description
          int mysql_insert_id(resource link_identifier);


      Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

      Parameters



      link_identifier                         The MySQL connection. If the link identifier is not specified, the last link opened by
                                              mysql_connect is assumed. If no such link is found, it will try to create one as if
                                              mysql_connect was called with no arguments. If no connection is found or established, an
                                              E_WARNING level error is generated.


      Return Values

      The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an
      AUTO_INCREMENT value, or FALSE if no MySQL connection was established.

      Examples


      Example 1.38. mysql_insert_id example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      if (!$link) {
          die('Could not connect: ' . mysql_error());
      }
      mysql_select_db('mydb');
      mysql_query("INSERT INTO mytable (product) values ('kossu')");
      printf("Last inserted record has id %dn", mysql_insert_id());
      ?>




      Notes

               Caution
               mysql_insert_id will convert the return type of the native MySQL C API function mysql_insert_id() to a
               type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the con-
               version may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL
               query. For more information about PHP's maximum integer values, please see the integer documentation.

               Note



                                                                  40
MySQL Extension (mysql)




               Because mysql_insert_id acts on the last performed query, be sure to call mysql_insert_id immediately after
               the query that generates the value.

               Note
               The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated
               AUTO_INCREMENT value, and is not reset between queries.

      See Also


      mysql_query
      mysql_info

1.4.32. mysql_list_dbs
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_list_dbs

           List databases available on a MySQL server


      Description
          resource mysql_list_dbs(resource link_identifier);


      Returns a result pointer containing the databases available from the current mysql daemon.

      Parameters



      link_identifier                       The MySQL connection. If the link identifier is not specified, the last link opened by
                                            mysql_connect is assumed. If no such link is found, it will try to create one as if
                                            mysql_connect was called with no arguments. If no connection is found or established, an
                                            E_WARNING level error is generated.


      Return Values

      Returns a result pointer resource on success, or FALSE on failure. Use the mysql_tablename function to traverse this result pointer,
      or any function for result tables, such as mysql_fetch_array.

      Examples


      Example 1.39. mysql_list_dbs example

      <?php
      $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
      $db_list = mysql_list_dbs($link);
      while ($row = mysql_fetch_object($db_list)) {
            echo $row->Database . "n";
      }
      ?>




      The above example will output something similar to:


      database1
      database2


                                                                  41
MySQL Extension (mysql)



      database3




      Notes

               Note
               For backward compatibility, the following deprecated alias may be used: mysql_listdbs

      See Also


      mysql_db_name
      mysql_select_db

1.4.33. mysql_list_fields
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_list_fields

           List MySQL table fields


      Description
          resource mysql_list_fields(string database_name,
                                     string table_name,
                                     resource link_identifier);


      Retrieves information about the given table name.

      This function is deprecated. It is preferable to use mysql_query to issue a SQL SHOW COLUMNS FROM table [LIKE
      'name'] statement instead.

      Parameters



      database_name                         The name of the database that's being queried.

      table_name                            The name of the table that's being queried.

      link_identifier                       The MySQL connection. If the link identifier is not specified, the last link opened by
                                            mysql_connect is assumed. If no such link is found, it will try to create one as if
                                            mysql_connect was called with no arguments. If no connection is found or established, an
                                            E_WARNING level error is generated.


      Return Values

      A result pointer resource on success, or FALSE on failure.

      The returned result can be used with mysql_field_flags, mysql_field_len, mysql_field_name and
      mysql_field_type.

      Examples


      Example 1.40. Alternate to deprecated mysql_list_fields

      <?php


                                                                   42
MySQL Extension (mysql)



      $result = mysql_query("SHOW COLUMNS FROM sometable");
      if (!$result) {
          echo 'Could not run query: ' . mysql_error();
          exit;
      }
      if (mysql_num_rows($result) > 0) {
          while ($row = mysql_fetch_assoc($result)) {
              print_r($row);
          }
      }
      ?>




      The above example will output something similar to:


      Array
      (
          [Field] => id
          [Type] => int(7)
          [Null] =>
          [Key] => PRI
          [Default] =>
          [Extra] => auto_increment
      )
      Array
      (
          [Field] => email
          [Type] => varchar(100)
          [Null] =>
          [Key] =>
          [Default] =>
          [Extra] =>
      )




      Notes

               Note
               For backward compatibility, the following deprecated alias may be used: mysql_listfields

      See Also


      mysql_field_flags
      mysql_info

1.4.34. mysql_list_processes
      Copyright 1997-2008 the PHP Documentation Group.


      •    mysql_list_processes

           List MySQL processes


      Description
          resource mysql_list_processes(resource link_identifier);


      Retrieves the current MySQL server threads.

      Parameters



      link_identifier                      The MySQL connection. If the link identifier is not specified, the last link opened by


                                                                 43
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP
MySQL and PHP

More Related Content

What's hot

ArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release Notes
ArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release NotesArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release Notes
ArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release Notesprotect724rkeer
 
Hash join in MySQL 8
Hash join in MySQL 8Hash join in MySQL 8
Hash join in MySQL 8Erik Frøseth
 
Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)
Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)
Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)Taoufik AIT HSAIN
 
Hp vertica 7.2.x_complete_documentation
Hp vertica 7.2.x_complete_documentationHp vertica 7.2.x_complete_documentation
Hp vertica 7.2.x_complete_documentationEric Javier Espino Man
 
Apache doc
Apache docApache doc
Apache docReka
 

What's hot (6)

ArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release Notes
ArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release NotesArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release Notes
ArcSight ArcSight Model Import Connector for RepSM 7.1.7.7607.0 Release Notes
 
Hash join in MySQL 8
Hash join in MySQL 8Hash join in MySQL 8
Hash join in MySQL 8
 
Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)
Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)
Obiee 11.1.7.0 step by step installation on linux (rhel – red hat)
 
Hp vertica 7.2.x_complete_documentation
Hp vertica 7.2.x_complete_documentationHp vertica 7.2.x_complete_documentation
Hp vertica 7.2.x_complete_documentation
 
Apache doc
Apache docApache doc
Apache doc
 
final doc
final docfinal doc
final doc
 

Viewers also liked

txConnect SSL and Domain Explained
txConnect SSL and Domain ExplainedtxConnect SSL and Domain Explained
txConnect SSL and Domain Explainedwebhostingguy
 
Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea
Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea
Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea webhostingguy
 
Outsourced hosted solutions- Pro's
Outsourced hosted solutions- Pro's Outsourced hosted solutions- Pro's
Outsourced hosted solutions- Pro's webhostingguy
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Productswebhostingguy
 
Website Design and Hosting
Website Design and HostingWebsite Design and Hosting
Website Design and Hostingwebhostingguy
 
Getting Started With Dedicated
Getting Started With Dedicated Getting Started With Dedicated
Getting Started With Dedicated webhostingguy
 

Viewers also liked (9)

txConnect SSL and Domain Explained
txConnect SSL and Domain ExplainedtxConnect SSL and Domain Explained
txConnect SSL and Domain Explained
 
Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea
Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea
Feb. 9, 2010 ICACT 2010@Phoenix Park, Korea
 
Outsourced hosted solutions- Pro's
Outsourced hosted solutions- Pro's Outsourced hosted solutions- Pro's
Outsourced hosted solutions- Pro's
 
Parallels Hosting Products
Parallels Hosting ProductsParallels Hosting Products
Parallels Hosting Products
 
Estado Del Arte Supply Chain
Estado Del Arte Supply ChainEstado Del Arte Supply Chain
Estado Del Arte Supply Chain
 
OPTIK NERVE
OPTIK NERVEOPTIK NERVE
OPTIK NERVE
 
Website Design and Hosting
Website Design and HostingWebsite Design and Hosting
Website Design and Hosting
 
Getting Started With Dedicated
Getting Started With Dedicated Getting Started With Dedicated
Getting Started With Dedicated
 
Modeling Supply Chain
Modeling Supply ChainModeling Supply Chain
Modeling Supply Chain
 

Similar to MySQL and PHP

Innodb 1.1 for mysql 5.5 user's guide
Innodb 1.1 for mysql 5.5 user's guideInnodb 1.1 for mysql 5.5 user's guide
Innodb 1.1 for mysql 5.5 user's guidemysqlpub
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guidewebhostingguy
 
Oracle Database Licensing Rules
Oracle Database Licensing RulesOracle Database Licensing Rules
Oracle Database Licensing RulesDoddi Priyambodo
 
App v 4.6 sp1 trial guide
App v 4.6 sp1 trial guideApp v 4.6 sp1 trial guide
App v 4.6 sp1 trial guideKishore Kumar
 
Informatica Command Line Statements
Informatica Command Line StatementsInformatica Command Line Statements
Informatica Command Line Statementsmnsk80
 
APACHE
APACHEAPACHE
APACHEARJUN
 
Microsoft WebsiteSpark & Windows Platform Installer
Microsoft WebsiteSpark & Windows Platform InstallerMicrosoft WebsiteSpark & Windows Platform Installer
Microsoft WebsiteSpark & Windows Platform InstallerGeorge Kanellopoulos
 
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfWeb sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfaquacareser
 
Whats new Primavera P6 Professional 15.2?
Whats new Primavera P6 Professional 15.2?Whats new Primavera P6 Professional 15.2?
Whats new Primavera P6 Professional 15.2?p6academy
 
Oracle database 12c client release notes
Oracle database 12c client release notesOracle database 12c client release notes
Oracle database 12c client release notesbupbechanhgmail
 
Oracle REST Data Services
Oracle REST Data ServicesOracle REST Data Services
Oracle REST Data ServicesChris Muir
 
ArcSight Connector Appliance 6.4 Patch 1 Release Notes
ArcSight Connector Appliance 6.4 Patch 1 Release NotesArcSight Connector Appliance 6.4 Patch 1 Release Notes
ArcSight Connector Appliance 6.4 Patch 1 Release NotesProtect724tk
 
using-integrations-oracle-integration.pdf
using-integrations-oracle-integration.pdfusing-integrations-oracle-integration.pdf
using-integrations-oracle-integration.pdfNalamalpuBhakthavats
 
Day 2-presentation
Day 2-presentationDay 2-presentation
Day 2-presentationDeb Forsten
 
PHP (Hypertext Preprocessor)
PHP (Hypertext Preprocessor)PHP (Hypertext Preprocessor)
PHP (Hypertext Preprocessor)aNumak & Company
 

Similar to MySQL and PHP (20)

Workbench en
Workbench enWorkbench en
Workbench en
 
Innodb 1.1 for mysql 5.5 user's guide
Innodb 1.1 for mysql 5.5 user's guideInnodb 1.1 for mysql 5.5 user's guide
Innodb 1.1 for mysql 5.5 user's guide
 
MySQL and memcached Guide
MySQL and memcached GuideMySQL and memcached Guide
MySQL and memcached Guide
 
Oracle Database Licensing Rules
Oracle Database Licensing RulesOracle Database Licensing Rules
Oracle Database Licensing Rules
 
App v 4.6 sp1 trial guide
App v 4.6 sp1 trial guideApp v 4.6 sp1 trial guide
App v 4.6 sp1 trial guide
 
jfx
jfxjfx
jfx
 
Informatica Command Line Statements
Informatica Command Line StatementsInformatica Command Line Statements
Informatica Command Line Statements
 
APACHE
APACHEAPACHE
APACHE
 
Microsoft WebsiteSpark & Windows Platform Installer
Microsoft WebsiteSpark & Windows Platform InstallerMicrosoft WebsiteSpark & Windows Platform Installer
Microsoft WebsiteSpark & Windows Platform Installer
 
Oracle license management training part 4
Oracle license management training part 4Oracle license management training part 4
Oracle license management training part 4
 
D3 MVS Toolkit
D3 MVS ToolkitD3 MVS Toolkit
D3 MVS Toolkit
 
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfWeb sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
 
Whats new Primavera P6 Professional 15.2?
Whats new Primavera P6 Professional 15.2?Whats new Primavera P6 Professional 15.2?
Whats new Primavera P6 Professional 15.2?
 
Oracle database 12c client release notes
Oracle database 12c client release notesOracle database 12c client release notes
Oracle database 12c client release notes
 
Peoplesoft technical consultant interview questions
Peoplesoft technical consultant interview questionsPeoplesoft technical consultant interview questions
Peoplesoft technical consultant interview questions
 
Oracle REST Data Services
Oracle REST Data ServicesOracle REST Data Services
Oracle REST Data Services
 
ArcSight Connector Appliance 6.4 Patch 1 Release Notes
ArcSight Connector Appliance 6.4 Patch 1 Release NotesArcSight Connector Appliance 6.4 Patch 1 Release Notes
ArcSight Connector Appliance 6.4 Patch 1 Release Notes
 
using-integrations-oracle-integration.pdf
using-integrations-oracle-integration.pdfusing-integrations-oracle-integration.pdf
using-integrations-oracle-integration.pdf
 
Day 2-presentation
Day 2-presentationDay 2-presentation
Day 2-presentation
 
PHP (Hypertext Preprocessor)
PHP (Hypertext Preprocessor)PHP (Hypertext Preprocessor)
PHP (Hypertext Preprocessor)
 

More from webhostingguy

Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Frameworkwebhostingguy
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3webhostingguy
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serverswebhostingguy
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidationwebhostingguy
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreementwebhostingguy
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...webhostingguy
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...webhostingguy
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructurewebhostingguy
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.pptwebhostingguy
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy webhostingguy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandiserswebhostingguy
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mbwebhostingguy
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...webhostingguy
 
Getting Started Guide
Getting Started GuideGetting Started Guide
Getting Started Guidewebhostingguy
 

More from webhostingguy (20)

File Upload
File UploadFile Upload
File Upload
 
Running and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test FrameworkRunning and Developing Tests with the Apache::Test Framework
Running and Developing Tests with the Apache::Test Framework
 
Novell® iChain® 2.3
Novell® iChain® 2.3Novell® iChain® 2.3
Novell® iChain® 2.3
 
Load-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web serversLoad-balancing web servers Load-balancing web servers
Load-balancing web servers Load-balancing web servers
 
SQL Server 2008 Consolidation
SQL Server 2008 ConsolidationSQL Server 2008 Consolidation
SQL Server 2008 Consolidation
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
What is mod_perl?
What is mod_perl?What is mod_perl?
What is mod_perl?
 
Master Service Agreement
Master Service AgreementMaster Service Agreement
Master Service Agreement
 
Notes8
Notes8Notes8
Notes8
 
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...PHP and MySQL PHP Written as a set of CGI binaries in C in ...
PHP and MySQL PHP Written as a set of CGI binaries in C in ...
 
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...Dell Reference Architecture Guide Deploying Microsoft® SQL ...
Dell Reference Architecture Guide Deploying Microsoft® SQL ...
 
Managing Diverse IT Infrastructure
Managing Diverse IT InfrastructureManaging Diverse IT Infrastructure
Managing Diverse IT Infrastructure
 
Web design for business.ppt
Web design for business.pptWeb design for business.ppt
Web design for business.ppt
 
IT Power Management Strategy
IT Power Management Strategy IT Power Management Strategy
IT Power Management Strategy
 
Excel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for MerchandisersExcel and SQL Quick Tricks for Merchandisers
Excel and SQL Quick Tricks for Merchandisers
 
OLUG_xen.ppt
OLUG_xen.pptOLUG_xen.ppt
OLUG_xen.ppt
 
Microsoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 MbMicrosoft PowerPoint presentation 2.175 Mb
Microsoft PowerPoint presentation 2.175 Mb
 
Reseller's Guide
Reseller's GuideReseller's Guide
Reseller's Guide
 
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
Installation of MySQL 5.1 Cluster Software on the Solaris 10 ...
 
Getting Started Guide
Getting Started GuideGetting Started Guide
Getting Started Guide
 

MySQL and PHP

  • 2. MySQL and PHP Reference Abstract This manual describes the PHP extensions and interfacs that can be used with MySQL. Document generated on: 2010-04-19 (revision: 20085) Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. This software and related documentation are provided under a license agreement containing restrictions on use and disclosure and are protected by intel- lectual property laws. Except as expressly permitted in your license agreement or allowed by law, you may not use, copy, reproduce, translate, broadcast, modify, license, transmit, distribute, exhibit, perform, publish, or display any part, in any form, or by any means. Reverse engineering, disassembly, or decompilation of this software, unless required by law for interoperability, is prohibited. The information contained herein is subject to change without notice and is not warranted to be error-free. If you find any errors, please report them to us in writing. If this software or related documentation is delivered to the U.S. Government or anyone licensing it on behalf of the U.S. Government, the following no- tice is applicable: U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data delivered to U.S. Government customers are "commercial computer software" or "commercial technical data" pursuant to the applicable Federal Acquisition Regulation and agency-specific sup- plemental regulations. As such, the use, duplication, disclosure, modification, and adaptation shall be subject to the restrictions and license terms set forth in the applicable Government contract, and, to the extent applicable by the terms of the Government contract, the additional rights set forth in FAR 52.227-19, Commercial Computer Software License (December 2007). Oracle USA, Inc., 500 Oracle Parkway, Redwood City, CA 94065. This software is developed for general use in a variety of information management applications. It is not developed or intended for use in any inherently dangerous applications, including applications which may create a risk of personal injury. If you use this software in dangerous applications, then you shall be responsible to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of this software. Oracle Corporation and its affiliates disclaim any liability for any damages caused by use of this software in dangerous applications. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. MySQL is a trademark of Oracle Corporation and/or its affiliates, and shall not be used without Oracle's express written authorization. Other names may be trademarks of their respective owners. This software and documentation may provide access to or information on content, products, and services from third parties. Oracle Corporation and its affiliates are not responsible for and expressly disclaim all warranties of any kind with respect to third-party content, products, and services. Oracle Cor- poration and its affiliates will not be responsible for any loss, costs, or damages incurred due to your access to or use of third-party content, products, or services. This document in any form, software or printed matter, contains proprietary information that is the exclusive property of Oracle. Your access to and use of this material is subject to the terms and conditions of your Oracle Software License and Service Agreement, which has been executed and with which you agree to comply. This document and information contained herein may not be disclosed, copied, reproduced, or distributed to anyone outside Oracle without prior written consent of Oracle or as specifically provided below. This document is not part of your license agreement nor can it be incorporated into any contractual agreement with Oracle or its subsidiaries or affiliates. This documentation is NOT distributed under a GPL license. Use of this documentation is subject to the following terms: You may create a printed copy of this documentation solely for your own personal use. Conversion to other formats is allowed as long as the actual con- tent is not altered or edited in any way. You shall not publish or distribute this documentation in any form or on any media, except if you distribute the documentation in a manner similar to how Oracle disseminates it (that is, electronically for download on a Web site with the software) or on a CD-ROM or similar medium, provided however that the documentation is disseminated together with the software on the same medium. Any other use, such as any dissemination of printed copies or use of this documentation, in whole or in part, in another publication, requires the prior written consent from an au- thorized representative of Oracle. Oracle and/or its affiliates reserve any and all rights to this documentation not expressly granted above. For more information on the terms of this license, for details on how the MySQL documentation is built and produced, or if you are interested in doing a translation, please visit http://www.mysql.com/company/contact/. For additional licensing information, including licenses for libraries used by MySQL, see Preface, Notes, Licenses. If you want help with using MySQL, please visit either the MySQL Forums or MySQL Mailing Lists where you can discuss your issues with other MySQL users. For additional documentation on MySQL products, including translations of the documentation into other languages, and downloadable versions in vari- ety of formats, including HTML and PDF formats, see the MySQL Documentation Library.
  • 3.
  • 4. Preface PHP is a server-side, HTML-embedded scripting language that may be used to create dynamic Web pages. It is available for most oper- ating systems and Web servers, and can access most common databases, including MySQL. PHP may be run as a separate program or compiled as a module for use with the Apache Web server. PHP actually provides two different MySQL API extensions: • mysql: Available for PHP versions 4 and 5, this extension is intended for use with MySQL versions prior to MySQL 4.1. This ex- tension does not support the improved authentication protocol used in MySQL 4.1, nor does it support prepared statements or mul- tiple statements. If you wish to use this extension with MySQL 4.1, you will likely want to configure the MySQL server to use the - -old-passwords option (see Client does not support authentication protocol). This extension is docu- mented on the PHP Web site at http://php.net/mysql. • Chapter 2, MySQL Improved Extension (Mysqli) - Stands for “MySQL, Improved”; this extension is available only in PHP 5. It is intended for use with MySQL 4.1.1 and later. This extension fully supports the authentication protocol used in MySQL 5.0, as well as the Prepared Statements and Multiple Statements APIs. In addition, this extension provides an advanced, object-oriented pro- gramming interface. You can read the documentation for the mysqli extension at http://php.net/mysqli. Helpful article can be found at http://devzone.zend.com/node/view/id/686 and http://devzone.zend.com/node/view/id/687. If you're experiencing problems with enabling both the mysql and the mysqli extension when building PHP on Linux yourself, see Chapter 7, Enabling Both mysql and mysqli in PHP. The PHP distribution and documentation are available from the PHP Web site. Preface MySQL Enterprise subscribers will find more information about MySQL and PHP in the Knowledge Base art- icles found at PHP. Access to the MySQL Knowledge Base collection of articles is one of the advantages of subscribing to MySQL Enterprise. For more information, see ht- tp://www.mysql.com/products/enterprise/knowledgebase.html. Portions of this section are Copyright (c) 1997-2008 the PHP Documentation Group This material may be distributed only subject to the terms and conditions set forth in the Creative Commons Attribution 3.0 License or later. A copy of the Creative Commons Attribu- tion 3.0 license is distributed with this manual. The latest version is presently available at This material may be distributed only subject to the terms and conditio ns set forth in the Open Publication License, v1.0.8 or later (the latest version is presently available at ht- tp://www.opencontent.org/openpub/). iv
  • 5. Chapter 1. MySQL Extension (mysql) Copyright 1997-2008 the PHP Documentation Group. These functions allow you to access MySQL database servers. More information about MySQL can be found at ht- tp://www.mysql.com/. Documentation for MySQL can be found at http://dev.mysql.com/doc/. For an overview of MySQL database connectivity terms and products see Section 2.2, “Overview”. 1.1. Installing/Configuring Copyright 1997-2008 the PHP Documentation Group. 1.1.1. Requirements Copyright 1997-2008 the PHP Documentation Group. In order to have these functions available, you must compile PHP with MySQL support. 1.1.2. Installation Copyright 1997-2008 the PHP Documentation Group. For compiling, simply use the --with-mysql[=DIR] configuration option where the optional [DIR] points to the MySQL installa- tion directory. Although this MySQL extension is compatible with MySQL 4.1.0 and greater, it doesn't support the extra functionality that these ver- sions provide. For that, use the MySQLi extension. If you would like to install the mysql extension along with the mysqli extension you have to use the same client library to avoid any conflicts. 1.1.2.1. Installation on Linux Systems Copyright 1997-2008 the PHP Documentation Group. 1.1.2.1.1. PHP 4 Copyright 1997-2008 the PHP Documentation Group. The option --with-mysql is enabled by default. This default behavior may be disabled with the --without-mysql configure op- tion. If MySQL is enabled without specifying the path to the MySQL install DIR, PHP will use the bundled MySQL client libraries. Users who run other applications that use MySQL (for example, auth-mysql) should not use the bundled library, but rather specify the path to MySQL's install directory, like so: --with-mysql=/path/to/mysql. This will force PHP to use the client libraries in- stalled by MySQL, thus avoiding any conflicts. 1.1.2.1.2. PHP 5+ Copyright 1997-2008 the PHP Documentation Group. MySQL is not enabled by default, nor is the MySQL library bundled with PHP. Read this FAQ for details on why. Use the - -with-mysql[=DIR] configure option to include MySQL support. You can download headers and libraries from ht- tp://www.mysql.com/. 1.1.2.2. Installation on Windows Systems Copyright 1997-2008 the PHP Documentation Group. 1.1.2.2.1. PHP 4 1
  • 6. MySQL Extension (mysql) Copyright 1997-2008 the PHP Documentation Group. The PHP MySQL extension is compiled into PHP. 1.1.2.2.2. PHP 5+ Copyright 1997-2008 the PHP Documentation Group. MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH. See the FAQ titled "How do I add my PHP directory to the PATH on Windows" for information on how to do this. Although copying libmysql.dll to the Windows system directory also works (because the system directory is by default in the system's PATH), it's not recommended. As with enabling any PHP extension (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located. See also the Manual Windows Installation Instructions. An example extension_dir value for PHP 5 is c:phpext Note If when starting the web server an error similar to the following occurs: "Unable to load dynamic library './php_mysql.dll'", this is because php_mysql.dll and/or libmysql.dll cannot be found by the system. 1.1.2.3. MySQL Installation Notes Copyright 1997-2008 the PHP Documentation Group. Warning Crashes and startup problems of PHP may be encountered when loading this extension in conjunction with the recode ex- tension. See the recode extension for more information. Note If you need charsets other than latin (default), you have to install external (not bundled) libmysql with compiled charset support. 1.1.3. Runtime Configuration Copyright 1997-2008 the PHP Documentation Group. The behaviour of these functions is affected by settings in php.ini. Table 1.1. MySQL Configuration Options Name Default Changeable Changelog mysql.allow_persistent "1" PHP_INI_SYSTEM mysql.max_persistent "-1" PHP_INI_SYSTEM mysql.max_links "-1" PHP_INI_SYSTEM mysql.trace_mode "0" PHP_INI_ALL Available since PHP 4.3.0. mysql.default_port NULL PHP_INI_ALL mysql.default_socket NULL PHP_INI_ALL Available since PHP 4.0.1. mysql.default_host NULL PHP_INI_ALL mysql.default_user NULL PHP_INI_ALL mysql.default_password NULL PHP_INI_ALL mysql.connect_timeout "60" PHP_INI_ALL PHP_INI_SYSTEM in PHP <= 4.3.2. Available since PHP 4.3.0. 2
  • 7. MySQL Extension (mysql) For further details and definitions of the PHP_INI_* modes, see the configuration.changes.modes. Here's a short explanation of the configuration directives. mysql.allow_persistent Whether to allow persistent connections to MySQL. boolean mysql.max_persistent in- The maximum number of persistent MySQL connections per process. teger mysql.max_links integer The maximum number of MySQL connections per process, including persistent connections. mysql.trace_mode boolean Trace mode. When mysql.trace_mode is enabled, warnings for table/index scans, non free result sets, and SQL-Errors will be displayed. (Introduced in PHP 4.3.0) mysql.default_port string The default TCP port number to use when connecting to the database server if no other port is specified. If no default is specified, the port will be obtained from the MYSQL_TCP_PORT envir- onment variable, the mysql-tcp entry in /etc/services or the compile-time MYSQL_PORT constant, in that order. Win32 will only use the MYSQL_PORT constant. mysql.default_socket The default socket name to use when connecting to a local database server if no other socket string name is specified. mysql.default_host string The default server host to use when connecting to the database server if no other host is specified. Doesn't apply in SQL safe mode. mysql.default_user string The default user name to use when connecting to the database server if no other name is spe- cified. Doesn't apply in SQL safe mode. mysql.default_password The default password to use when connecting to the database server if no other password is spe- string cified. Doesn't apply in SQL safe mode. mysql.connect_timeout in- Connect timeout in seconds. On Linux this timeout is also used for waiting for the first answer teger from the server. 1.1.4. Resource Types Copyright 1997-2008 the PHP Documentation Group. There are two resource types used in the MySQL module. The first one is the link identifier for a database connection, the second a re- source which holds the result of a query. 1.2. Predefined Constants Copyright 1997-2008 the PHP Documentation Group. The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime. Since PHP 4.3.0 it is possible to specify additional client flags for the mysql_connect and mysql_pconnect functions. The fol- lowing constants are defined: Table 1.2. MySQL client constants Constant Description MYSQL_CLIENT_COMPRESS Use compression protocol MYSQL_CLIENT_IGNORE_SPACE Allow space after function names MYSQL_CLIENT_INTERACTIVE Allow interactive_timeout seconds (instead of wait_timeout) of inactivity before closing the connection. MYSQL_CLIENT_SSL Use SSL encryption. This flag is only available with version 4.x of the MySQL client library or newer. Version 3.23.x is bundled both with PHP 4 and Windows binaries of PHP 5. 3
  • 8. MySQL Extension (mysql) The function mysql_fetch_array uses a constant for the different types of result arrays. The following constants are defined: Table 1.3. MySQL fetch constants Constant Description MYSQL_ASSOC Columns are returned into the array having the fieldname as the ar- ray index. MYSQL_BOTH Columns are returned into the array having both a numerical index and the fieldname as the array index. MYSQL_NUM Columns are returned into the array having a numerical index to the fields. This index starts with 0, the first field in the result. 1.3. Examples Copyright 1997-2008 the PHP Documentation Group. 1.3.1. Basic This simple example shows how to connect, execute a query, print resulting rows and disconnect from a MySQL database. Example 1.1. MySQL extension overview example Copyright 1997-2008 the PHP Documentation Group. <?php // Connecting, selecting database $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') or die('Could not connect: ' . mysql_error()); echo 'Connected successfully'; mysql_select_db('my_database') or die('Could not select database'); // Performing SQL query $query = 'SELECT * FROM my_table'; $result = mysql_query($query) or die('Query failed: ' . mysql_error()); // Printing results in HTML echo "<table>n"; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "t<tr>n"; foreach ($line as $col_value) { echo "tt<td>$col_value</td>n"; } echo "t</tr>n"; } echo "</table>n"; // Free resultset mysql_free_result($result); // Closing connection mysql_close($link); ?> 1.4. MySQL Functions Copyright 1997-2008 the PHP Documentation Group. Note Most MySQL functions accept link_identifier as the last optional parameter. If it is not provided, last opened con- nection is used. If it doesn't exist, connection is tried to establish with default parameters defined in php.ini. If it is not successful, functions return FALSE . 1.4.1. mysql_affected_rows 4
  • 9. MySQL Extension (mysql) Copyright 1997-2008 the PHP Documentation Group. • mysql_affected_rows Get number of affected rows in previous MySQL operation Description int mysql_affected_rows(resource link_identifier); Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns the number of affected rows on success, and -1 if the last query failed. If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2. When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows may not actually equal the number of rows matched, only the number of rows that were literally af- fected by the query. The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records. Examples Example 1.2. mysql_affected_rows example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); /* this should return the correct numbers of deleted records */ mysql_query('DELETE FROM mytable WHERE id < 10'); printf("Records deleted: %dn", mysql_affected_rows()); /* with a where clause that is never true, it should return 0 */ mysql_query('DELETE FROM mytable WHERE 0'); printf("Records deleted: %dn", mysql_affected_rows()); ?> The above example will output something similar to: Records deleted: 10 Records deleted: 0 5
  • 10. MySQL Extension (mysql) Example 1.3. mysql_affected_rows example using transactions <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); /* Update records */ mysql_query("UPDATE mytable SET used=1 WHERE id < 10"); printf ("Updated records: %dn", mysql_affected_rows()); mysql_query("COMMIT"); ?> The above example will output something similar to: Updated Records: 10 Notes Transactions If you are using transactions, you need to call mysql_affected_rows after your INSERT, UPDATE, or DELETE query, not after the COMMIT. SELECT Statements To retrieve the number of rows returned by a SELECT, it is possible to use mysql_num_rows. Cascaded Foreign Keys mysql_affected_rows does not count rows affected implicitly through the use of ON DELETE CASCADE and/or ON UPDATE CASCADE in foreign key constraints. See Also mysql_num_rows mysql_info 1.4.2. mysql_client_encoding Copyright 1997-2008 the PHP Documentation Group. • mysql_client_encoding Returns the name of the character set Description string mysql_client_encoding(resource link_identifier); Retrieves the character_set variable from MySQL. Parameters 6
  • 11. MySQL Extension (mysql) link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns the default character set name for the current connection. Examples Example 1.4. mysql_client_encoding example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $charset = mysql_client_encoding($link); echo "The current character set is: $charsetn"; ?> The above example will output something similar to: The current character set is: latin1 See Also mysql_set_charset mysql_real_escape_string 1.4.3. mysql_close Copyright 1997-2008 the PHP Documentation Group. • mysql_close Close MySQL connection Description bool mysql_close(resource link_identifier); mysql_close closes the non-persistent connection to the MySQL server that's associated with the specified link identifier. If link_identifier isn't specified, the last opened link is used. Using mysql_close isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. See also freeing resources. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by 7
  • 12. MySQL Extension (mysql) mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns TRUE on success or FALSE on failure. Examples Example 1.5. mysql_close example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?> The above example will output: Connected successfully Notes Note mysql_close will not close persistent links created by mysql_pconnect. See Also mysql_connect mysql_free_result 1.4.4. mysql_connect Copyright 1997-2008 the PHP Documentation Group. • mysql_connect Open a connection to a MySQL Server Description resource mysql_connect(string server= =ini_get("mysql.default_host"), string username= =ini_get("mysql.default_user"), string password= =ini_get("mysql.default_password"), bool new_link= =false, int client_flags= =0); Opens or reuses a connection to a MySQL server. Parameters 8
  • 13. MySQL Extension (mysql) server The MySQL server. It can also include a port number. e.g. "hostname:port" or a path to a local socket e.g. ":/path/to/socket" for the localhost. If the PHP directive mysql.default_host is undefined (default), then the default value is 'local- host:3306'. In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used. username The username. Default value is defined by mysql.default_user. In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used. password The password. Default value is defined by mysql.default_password. In SQL safe mode, this para- meter is ignored and empty password is used. new_link If a second call is made to mysql_connect with the same arguments, no new link will be es- tablished, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect always open a new link, even if mysql_connect was called before with the same parameters. In SQL safe mode, this parameter is ignored. client_flags The client_flags parameter can be a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL , MYSQL_CLIENT_COMPRESS , MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE . Read the section about Table 1.2, “MySQL client constants” for further information. In SQL safe mode, this para- meter is ignored. Return Values Returns a MySQL link identifier on success or FALSE on failure. Changelog Version Description 4.3.0 Added the client_flags parameter. 4.2.0 Added the new_link parameter. Examples Example 1.6. mysql_connect example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?> Example 1.7. mysql_connect example using hostname:port syntax <?php // we connect to example.com and port 3307 $link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); 9
  • 14. MySQL Extension (mysql) } echo 'Connected successfully'; mysql_close($link); // we connect to localhost at port 3307 $link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?> Example 1.8. mysql_connect example using ":/path/to/socket" syntax <?php // we connect to localhost and socket e.g. /tmp/mysql.sock //variant 1: ommit localhost $link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); // variant 2: with localhost $link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); ?> Notes Note Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to con- nect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as mysql.default_host string in your PHP configuration and leave the server field blank. Note The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly call- ing mysql_close. Note You can suppress the error message on failure by prepending a @ to the function name. Note Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock. See Also mysql_pconnect mysql_close 1.4.5. mysql_create_db 10
  • 15. MySQL Extension (mysql) Copyright 1997-2008 the PHP Documentation Group. • mysql_create_db Create a MySQL database Description bool mysql_create_db(string database_name, resource link_identifier); mysql_create_db attempts to create a new database on the server associated with the specified link identifier. Parameters database_name The name of the database being created. link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns TRUE on success or FALSE on failure. Examples Example 1.9. mysql_create_db alternative example The function mysql_create_db is deprecated. It is preferable to use mysql_query to issue a sql CREATE DATABASE statement instead. <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } $sql = 'CREATE DATABASE my_db'; if (mysql_query($sql, $link)) { echo "Database my_db created successfullyn"; } else { echo 'Error creating database: ' . mysql_error() . "n"; } ?> The above example will output something similar to: Database my_db created successfully Notes Note For backward compatibility, the following deprecated alias may be used: mysql_createdb 11
  • 16. MySQL Extension (mysql) Note This function will not be available if the MySQL extension was built against a MySQL 4.x client library. See Also mysql_query mysql_select_db 1.4.6. mysql_data_seek Copyright 1997-2008 the PHP Documentation Group. • mysql_data_seek Move internal result pointer Description bool mysql_data_seek(resource result, int row_number); mysql_data_seek moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc, would return that row. row_number starts at 0. The row_number should be a value in the range from 0 to mysql_num_rows - 1. However if the result set is empty (mysql_num_rows == 0), a seek to 0 will fail with a E_WARNING and mysql_data_seek will return FALSE . Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. row_number The desired row number of the new result pointer. Return Values Returns TRUE on success or FALSE on failure. Examples Example 1.10. mysql_data_seek example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('sample_db'); if (!$db_selected) { die('Could not select database: ' . mysql_error()); } $query = 'SELECT last_name, first_name FROM friends'; $result = mysql_query($query); if (!$result) { die('Query failed: ' . mysql_error()); } /* fetch rows in reverse order */ for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) { if (!mysql_data_seek($result, $i)) { echo "Cannot seek to row $i: " . mysql_error() . "n"; continue; } 12
  • 17. MySQL Extension (mysql) if (!($row = mysql_fetch_assoc($result))) { continue; } echo $row['last_name'] . ' ' . $row['first_name'] . "<br />n"; } mysql_free_result($result); ?> Notes Note The function mysql_data_seek can be used in conjunction only with mysql_query, not with mysql_unbuffered_query. See Also mysql_query mysql_num_rows mysql_fetch_row mysql_fetch_assoc mysql_fetch_array mysql_fetch_object 1.4.7. mysql_db_name Copyright 1997-2008 the PHP Documentation Group. • mysql_db_name Get result data Description string mysql_db_name(resource result, int row, mixed field); Retrieve the database name from a call to mysql_list_dbs. Parameters result The result pointer from a call to mysql_list_dbs. row The index into the result set. field The field name. Return Values Returns the database name on success, and FALSE on failure. If FALSE is returned, use mysql_error to determine the nature of the error. Examples Example 1.11. mysql_db_name example 13
  • 18. MySQL Extension (mysql) <?php error_reporting(E_ALL); $link = mysql_connect('dbhost', 'username', 'password'); $db_list = mysql_list_dbs($link); $i = 0; $cnt = mysql_num_rows($db_list); while ($i < $cnt) { echo mysql_db_name($db_list, $i) . "n"; $i++; } ?> Notes Note For backward compatibility, the following deprecated alias may be used: mysql_dbname See Also mysql_list_dbs mysql_tablename 1.4.8. mysql_db_query Copyright 1997-2008 the PHP Documentation Group. • mysql_db_query Send a MySQL query Description resource mysql_db_query(string database, string query, resource link_identifier); mysql_db_query selects a database, and executes a query on it. Warning This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. Parameters database The name of the database that will be selected. query The MySQL query. Data inside the query should be properly escaped. link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns a positive MySQL result resource to the query result, or FALSE on error. The function also returns TRUE / FALSE for 14
  • 19. MySQL Extension (mysql) /UPDATE/DELETE queries to indicate success/failure. Changelog Version Description 5.3.0 This function now throws an E_DEPRECATED notice. 4.0.6 This function is deprecated, do not use this function. Use mysql_select_db and mysql_query instead. Examples Example 1.12. mysql_db_query alternative example <?php if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) { echo 'Could not connect to mysql'; exit; } if (!mysql_select_db('mysql_dbname', $link)) { echo 'Could not select database'; exit; } $sql = 'SELECT foo FROM bar WHERE id = 42'; $result = mysql_query($sql, $link); if (!$result) { echo "DB Error, could not query the databasen"; echo 'MySQL Error: ' . mysql_error(); exit; } while ($row = mysql_fetch_assoc($result)) { echo $row['foo']; } mysql_free_result($result); ?> Notes Note Be aware that this function does NOT switch back to the database you were connected before. In other words, you can't use this function to temporarily run a sql query on another database, you would have to manually switch back. Users are strongly encouraged to use the database.table syntax in their sql queries or mysql_select_db instead of this function. See Also mysql_query mysql_select_db 1.4.9. mysql_drop_db Copyright 1997-2008 the PHP Documentation Group. • mysql_drop_db Drop (delete) a MySQL database Description bool mysql_drop_db(string database_name, 15
  • 20. MySQL Extension (mysql) resource link_identifier); mysql_drop_db attempts to drop (remove) an entire database from the server associated with the specified link identifier. This func- tion is deprecated, it is preferable to use mysql_query to issue a sql DROP DATABASE statement instead. Parameters database_name The name of the database that will be deleted. link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns TRUE on success or FALSE on failure. Examples Example 1.13. mysql_drop_db alternative example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } $sql = 'DROP DATABASE my_db'; if (mysql_query($sql, $link)) { echo "Database my_db was successfully droppedn"; } else { echo 'Error dropping database: ' . mysql_error() . "n"; } ?> Notes Warning This function will not be available if the MySQL extension was built against a MySQL 4.x client library. Note For backward compatibility, the following deprecated alias may be used: mysql_dropdb See Also mysql_query 1.4.10. mysql_errno Copyright 1997-2008 the PHP Documentation Group. • mysql_errno Returns the numerical value of the error message from previous MySQL operation 16
  • 21. MySQL Extension (mysql) Description int mysql_errno(resource link_identifier); Returns the error number from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_errno to retrieve the error code. Note that this function only returns the error code from the most recently executed MySQL function (not including mysql_error and mysql_errno), so if you want to use it, make sure you check the value before calling another MySQL function. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns the error number from the last MySQL function, or 0 (zero) if no error occurred. Examples Example 1.14. mysql_errno example <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); if (!mysql_select_db("nonexistentdb", $link)) { echo mysql_errno($link) . ": " . mysql_error($link). "n"; } mysql_select_db("kossu", $link); if (!mysql_query("SELECT * FROM nonexistenttable", $link)) { echo mysql_errno($link) . ": " . mysql_error($link) . "n"; } ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist See Also mysql_error MySQL error codes 1.4.11. mysql_error Copyright 1997-2008 the PHP Documentation Group. • mysql_error Returns the text of the error message from previous MySQL operation 17
  • 22. MySQL Extension (mysql) Description string mysql_error(resource link_identifier); Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error and mysql_errno), so if you want to use it, make sure you check the value before calling another MySQL function. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns the error text from the last MySQL function, or '' (empty string) if no error occurred. Examples Example 1.15. mysql_error example <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password"); mysql_select_db("nonexistentdb", $link); echo mysql_errno($link) . ": " . mysql_error($link). "n"; mysql_select_db("kossu", $link); mysql_query("SELECT * FROM nonexistenttable", $link); echo mysql_errno($link) . ": " . mysql_error($link) . "n"; ?> The above example will output something similar to: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist See Also mysql_errno MySQL error codes 1.4.12. mysql_escape_string Copyright 1997-2008 the PHP Documentation Group. • mysql_escape_string Escapes a string for use in a mysql_query Description 18
  • 23. MySQL Extension (mysql) string mysql_escape_string(string unescaped_string); This function will escape the unescaped_string, so that it is safe to place it in a mysql_query. This function is deprecated. This function is identical to mysql_real_escape_string except that mysql_real_escape_string takes a connection handler and escapes the string according to the current character set. mysql_escape_string does not take a connection argument and does not respect the current charset setting. Warning This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged. Parameters unescaped_string The string that is to be escaped. Return Values Returns the escaped string. Changelog Version Description 5.3.0 This function now throws an E_DEPRECATED notice. 4.3.0 This function became deprecated, do not use this function. Instead, use mysql_real_escape_string. Examples Example 1.16. mysql_escape_string example <?php $item = "Zak's Laptop"; $escaped_item = mysql_escape_string($item); printf("Escaped string: %sn", $escaped_item); ?> The above example will output: Escaped string: Zak's Laptop Notes Note mysql_escape_string does not escape % and _. See Also mysql_real_escape_string 19
  • 24. MySQL Extension (mysql) addslashes The magic_quotes_gpc directive. 1.4.13. mysql_fetch_array Copyright 1997-2008 the PHP Documentation Group. • mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both Description array mysql_fetch_array(resource result, int result_type= =MYSQL_BOTH); Returns an array that corresponds to the fetched row and moves the internal data pointer ahead. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. result_type The type of array that is to be fetched. It's a constant and can take the following values: MYSQL_ASSOC , MYSQL_NUM , and MYSQL_BOTH . Return Values Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Us- ing MYSQL_ASSOC , you only get associative indices (as mysql_fetch_assoc works), using MYSQL_NUM , you only get number indices (as mysql_fetch_row works). If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you must use the numeric index of the column or make an alias for the column. For aliased columns, you cannot access the contents with the original column name. Examples Example 1.17. Query with aliased duplicate field names SELECT table1.field AS foo, table2.field AS bar FROM table1, table2 Example 1.18. mysql_fetch_array with MYSQL_NUM <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { printf("ID: %s Name: %s", $row[0], $row[1]); } mysql_free_result($result); ?> 20
  • 25. MySQL Extension (mysql) Example 1.19. mysql_fetch_array with MYSQL_ASSOC <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { printf("ID: %s Name: %s", $row["id"], $row["name"]); } mysql_free_result($result); ?> Example 1.20. mysql_fetch_array with MYSQL_BOTH <?php mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { printf ("ID: %s Name: %s", $row[0], $row["name"]); } mysql_free_result($result); ?> Notes Performance An important thing to note is that using mysql_fetch_array is not significantly slower than using mysql_fetch_row, while it provides a significant added value. Note Field names returned by this function are case-sensitive. Note This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_row mysql_fetch_assoc mysql_data_seek mysql_query 1.4.14. mysql_fetch_assoc Copyright 1997-2008 the PHP Documentation Group. • mysql_fetch_assoc Fetch a result row as an associative array 21
  • 26. MySQL Extension (mysql) Description array mysql_fetch_assoc(resource result); Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc is equivalent to calling mysql_fetch_array with MYSQL_ASSOC for the optional second parameter. It only returns an associative array. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. Return Values Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using mysql_fetch_row or add alias names. See the ex- ample at the mysql_fetch_array description about aliases. Examples Example 1.21. An expanded mysql_fetch_assoc example <?php $conn = mysql_connect("localhost", "mysql_user", "mysql_password"); if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; } if (!mysql_select_db("mydbname")) { echo "Unable to select mydbname: " . mysql_error(); exit; } $sql = "SELECT id as userid, fullname, userstatus FROM sometable WHERE userstatus = 1"; $result = mysql_query($sql); if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; } if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; } // While a row of data exists, put that row in $row as an associative array // Note: If you're expecting just one row, no need to use a loop // Note: If you put extract($row); inside the following loop, you'll // then create $userid, $fullname, and $userstatus while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; } mysql_free_result($result); ?> Notes Performance An important thing to note is that using mysql_fetch_assoc is not significantly slower than using mysql_fetch_row, while it provides a significant added value. 22
  • 27. MySQL Extension (mysql) Note Field names returned by this function are case-sensitive. Note This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_row mysql_fetch_array mysql_data_seek mysql_query mysql_error 1.4.15. mysql_fetch_field Copyright 1997-2008 the PHP Documentation Group. • mysql_fetch_field Get column information from a result and return as an object Description object mysql_fetch_field(resource result, int field_offset= =0); Returns an object containing field information. This function can be used to obtain information about fields in the provided query result. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. field_offset The numerical field offset. If the field offset is not specified, the next field that was not yet re- trieved by this function is retrieved. The field_offset starts at 0. Return Values Returns an object containing field information. The properties of the object are: • name - column name • table - name of the table the column belongs to • def - default value of the column • max_length - maximum length of the column • not_null - 1 if the column cannot be NULL • primary_key - 1 if the column is a primary key • unique_key - 1 if the column is a unique key • multiple_key - 1 if the column is a non-unique key 23
  • 28. MySQL Extension (mysql) • numeric - 1 if the column is numeric • blob - 1 if the column is a BLOB • type - the type of the column • unsigned - 1 if the column is unsigned • zerofill - 1 if the column is zero-filled Examples Example 1.22. mysql_fetch_field example <?php $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$conn) { die('Could not connect: ' . mysql_error()); } mysql_select_db('database'); $result = mysql_query('select * from table'); if (!$result) { die('Query failed: ' . mysql_error()); } /* get column metadata */ $i = 0; while ($i < mysql_num_fields($result)) { echo "Information for column $i:<br />n"; $meta = mysql_fetch_field($result, $i); if (!$meta) { echo "No information available<br />n"; } echo "<pre> blob: $meta->blob max_length: $meta->max_length multiple_key: $meta->multiple_key name: $meta->name not_null: $meta->not_null numeric: $meta->numeric primary_key: $meta->primary_key table: $meta->table type: $meta->type default: $meta->def unique_key: $meta->unique_key unsigned: $meta->unsigned zerofill: $meta->zerofill </pre>"; $i++; } mysql_free_result($result); ?> Notes Note Field names returned by this function are case-sensitive. See Also mysql_field_seek 1.4.16. mysql_fetch_lengths Copyright 1997-2008 the PHP Documentation Group. 24
  • 29. MySQL Extension (mysql) • mysql_fetch_lengths Get the length of each output in a result Description array mysql_fetch_lengths(resource result); Returns an array that corresponds to the lengths of each field in the last row fetched by MySQL. mysql_fetch_lengths stores the lengths of each result column in the last row returned by mysql_fetch_row, mysql_fetch_assoc, mysql_fetch_array, and mysql_fetch_object in an array, starting at offset 0. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. Return Values An array of lengths on success or FALSE on failure. Examples Example 1.23. A mysql_fetch_lengths example <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_assoc($result); $lengths = mysql_fetch_lengths($result); print_r($row); print_r($lengths); ?> The above example will output something similar to: Array ( [id] => 42 [email] => user@example.com ) Array ( [0] => 2 [1] => 16 ) See Also mysql_field_len mysql_fetch_row strlen 25
  • 30. MySQL Extension (mysql) 1.4.17. mysql_fetch_object Copyright 1997-2008 the PHP Documentation Group. • mysql_fetch_object Fetch a result row as an object Description object mysql_fetch_object(resource result, string class_name, array params); Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. class_name The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned. params An optional array of parameters to pass to the constructor for class_name objects. Return Values Returns an object with string properties that correspond to the fetched row, or FALSE if there are no more rows. Changelog Version Description 5.0.0 Added the ability to return as a different object. Examples Example 1.24. mysql_fetch_object example <?php mysql_connect("hostname", "user", "password"); mysql_select_db("mydb"); $result = mysql_query("select * from mytable"); while ($row = mysql_fetch_object($result)) { echo $row->user_id; echo $row->fullname; } mysql_free_result($result); ?> Example 1.25. mysql_fetch_object example <?php class foo { public $name; 26
  • 31. MySQL Extension (mysql) } mysql_connect("hostname", "user", "password"); mysql_select_db("mydb"); $result = mysql_query("select name from mytable limit 1"); $obj = mysql_fetch_object($result, 'foo'); var_dump($obj); ?> Notes Performance Speed-wise, the function is identical to mysql_fetch_array, and almost as quick as mysql_fetch_row (the dif- ference is insignificant). Note mysql_fetch_object is similar to mysql_fetch_array, with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are il- legal property names). Note Field names returned by this function are case-sensitive. Note This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_row mysql_data_seek mysql_query 1.4.18. mysql_fetch_row Copyright 1997-2008 the PHP Documentation Group. • mysql_fetch_row Get a result row as an enumerated array Description array mysql_fetch_row(resource result); Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. Return Values Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows. 27
  • 32. MySQL Extension (mysql) mysql_fetch_row fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0. Examples Example 1.26. Fetching one row with mysql_fetch_row <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_row($result); echo $row[0]; // 42 echo $row[1]; // the email value ?> Notes Note This function sets NULL fields to the PHP NULL value. See Also mysql_fetch_array mysql_fetch_assoc mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_result 1.4.19. mysql_field_flags Copyright 1997-2008 the PHP Documentation Group. • mysql_field_flags Get the flags associated with the specified field in a result Description string mysql_field_flags(resource result, int field_offset); mysql_field_flags returns the field flags of the specified field. The flags are reported as a single word per flag separated by a single space, so that you can split the returned value using explode. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. field_offset The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. 28
  • 33. MySQL Extension (mysql) Return Values Returns a string of flags associated with the result or FALSE on failure. The following flags are reported, if your version of MySQL is current enough to support them: "not_null", "primary_key", "unique_key", "multiple_key", "blob", "unsigned", "zerofill", "binary", "enum", "auto_increment" and "timestamp". Examples Example 1.27. A mysql_field_flags example <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $flags = mysql_field_flags($result, 0); echo $flags; print_r(explode(' ', $flags)); ?> The above example will output something similar to: not_null primary_key auto_increment Array ( [0] => not_null [1] => primary_key [2] => auto_increment ) Notes Note For backward compatibility, the following deprecated alias may be used: mysql_fieldflags See Also mysql_field_type mysql_field_len 1.4.20. mysql_field_len Copyright 1997-2008 the PHP Documentation Group. • mysql_field_len Returns the length of the specified field Description int mysql_field_len(resource result, int field_offset); 29
  • 34. MySQL Extension (mysql) mysql_field_len returns the length of the specified field. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. field_offset The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values The length of the specified field index on success or FALSE on failure. Examples Example 1.28. mysql_field_len example <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } // Will get the length of the id field as specified in the database // schema. $length = mysql_field_len($result, 0); echo $length; ?> Notes Note For backward compatibility, the following deprecated alias may be used: mysql_fieldlen See Also mysql_fetch_lengths strlen 1.4.21. mysql_field_name Copyright 1997-2008 the PHP Documentation Group. • mysql_field_name Get the name of the specified field in a result Description string mysql_field_name(resource result, int field_offset); mysql_field_name returns the name of the specified field index. Parameters 30
  • 35. MySQL Extension (mysql) result The result resource that is being evaluated. This result comes from a call to mysql_query. field_offset The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values The name of the specified field index on success or FALSE on failure. Examples Example 1.29. mysql_field_name example <?php /* The users table consists of three fields: * user_id * username * password. */ $link = @mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect to MySQL server: ' . mysql_error()); } $dbname = 'mydb'; $db_selected = mysql_select_db($dbname, $link); if (!$db_selected) { die("Could not set $dbname: " . mysql_error()); } $res = mysql_query('select * from users', $link); echo mysql_field_name($res, 0) . "n"; echo mysql_field_name($res, 2); ?> The above example will output: user_id password Notes Note Field names returned by this function are case-sensitive. Note For backward compatibility, the following deprecated alias may be used: mysql_fieldname See Also mysql_field_type mysql_field_len 1.4.22. mysql_field_seek Copyright 1997-2008 the PHP Documentation Group. 31
  • 36. MySQL Extension (mysql) • mysql_field_seek Set result pointer to a specified field offset Description bool mysql_field_seek(resource result, int field_offset); Seeks to the specified field offset. If the next call to mysql_fetch_field doesn't include a field offset, the field offset specified in mysql_field_seek will be returned. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. field_offset The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values Returns TRUE on success or FALSE on failure. See Also mysql_fetch_field 1.4.23. mysql_field_table Copyright 1997-2008 the PHP Documentation Group. • mysql_field_table Get name of the table the specified field is in Description string mysql_field_table(resource result, int field_offset); Returns the name of the table that the specified field is in. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. field_offset The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values The name of the table on success. Examples 32
  • 37. MySQL Extension (mysql) Example 1.30. A mysql_field_table example <?php $query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = countr // get the result from the DB $result = mysql_query($query); // Lists the table name and then the field name for ($i = 0; $i < mysql_num_fields($result); ++$i) { $table = mysql_field_table($result, $i); $field = mysql_field_name($result, $i); echo "$table: $fieldn"; } ?> Notes Note For backward compatibility, the following deprecated alias may be used: mysql_fieldtable See Also mysql_list_tables 1.4.24. mysql_field_type Copyright 1997-2008 the PHP Documentation Group. • mysql_field_type Get the type of the specified field in a result Description string mysql_field_type(resource result, int field_offset); mysql_field_type is similar to the mysql_field_name function. The arguments are identical, but the field type is returned in- stead. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. field_offset The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued. Return Values The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the MySQL documentation. Examples Example 1.31. mysql_field_type example 33
  • 38. MySQL Extension (mysql) <?php mysql_connect("localhost", "mysql_username", "mysql_password"); mysql_select_db("mysql"); $result = mysql_query("SELECT * FROM func"); $fields = mysql_num_fields($result); $rows = mysql_num_rows($result); $table = mysql_field_table($result, 0); echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)n"; echo "The table has the following fields:n"; for ($i=0; $i < $fields; $i++) { $type = mysql_field_type($result, $i); $name = mysql_field_name($result, $i); $len = mysql_field_len($result, $i); $flags = mysql_field_flags($result, $i); echo $type . " " . $name . " " . $len . " " . $flags . "n"; } mysql_free_result($result); mysql_close(); ?> The above example will output something similar to: Your 'func' table has 4 fields and 1 record(s) The table has the following fields: string name 64 not_null primary_key binary int ret 1 not_null string dl 128 not_null string type 9 not_null enum Notes Note For backward compatibility, the following deprecated alias may be used: mysql_fieldtype See Also mysql_field_name mysql_field_len 1.4.25. mysql_free_result Copyright 1997-2008 the PHP Documentation Group. • mysql_free_result Free result memory Description bool mysql_free_result(resource result); mysql_free_result will free all memory associated with the result identifier result. mysql_free_result only needs to be called if you are concerned about how much memory is being used for queries that return large result sets. All associated result memory is automatically freed at the end of the script's execution. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. 34
  • 39. MySQL Extension (mysql) Return Values Returns TRUE on success or FALSE on failure. If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries. Examples Example 1.32. A mysql_free_result example <?php $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } /* Use the result, assuming we're done with it afterwards */ $row = mysql_fetch_assoc($result); /* Now we free up the result and continue on with our script */ mysql_free_result($result); echo $row['id']; echo $row['email']; ?> Notes Note For backward compatibility, the following deprecated alias may be used: mysql_freeresult See Also mysql_query is_resource 1.4.26. mysql_get_client_info Copyright 1997-2008 the PHP Documentation Group. • mysql_get_client_info Get MySQL client info Description string mysql_get_client_info(); mysql_get_client_info returns a string that represents the client library version. Return Values The MySQL client version. Examples Example 1.33. mysql_get_client_info example 35
  • 40. MySQL Extension (mysql) <?php printf("MySQL client info: %sn", mysql_get_client_info()); ?> The above example will output something similar to: MySQL client info: 3.23.39 See Also mysql_get_host_info mysql_get_proto_info mysql_get_server_info 1.4.27. mysql_get_host_info Copyright 1997-2008 the PHP Documentation Group. • mysql_get_host_info Get MySQL host info Description string mysql_get_host_info(resource link_identifier); Describes the type of connection in use for the connection, including the server host name. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns a string describing the type of MySQL connection in use for the connection or FALSE on failure. Examples Example 1.34. mysql_get_host_info example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } printf("MySQL host info: %sn", mysql_get_host_info()); ?> 36
  • 41. MySQL Extension (mysql) The above example will output something similar to: MySQL host info: Localhost via UNIX socket See Also mysql_get_client_info mysql_get_proto_info mysql_get_server_info 1.4.28. mysql_get_proto_info Copyright 1997-2008 the PHP Documentation Group. • mysql_get_proto_info Get MySQL protocol info Description int mysql_get_proto_info(resource link_identifier); Retrieves the MySQL protocol. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns the MySQL protocol on success or FALSE on failure. Examples Example 1.35. mysql_get_proto_info example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } printf("MySQL protocol version: %sn", mysql_get_proto_info()); ?> The above example will output something similar to: MySQL protocol version: 10 37
  • 42. MySQL Extension (mysql) See Also mysql_get_client_info mysql_get_host_info mysql_get_server_info 1.4.29. mysql_get_server_info Copyright 1997-2008 the PHP Documentation Group. • mysql_get_server_info Get MySQL server info Description string mysql_get_server_info(resource link_identifier); Retrieves the MySQL server version. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns the MySQL server version on success or FALSE on failure. Examples Example 1.36. mysql_get_server_info example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } printf("MySQL server version: %sn", mysql_get_server_info()); ?> The above example will output something similar to: MySQL server version: 4.0.1-alpha See Also 38
  • 43. MySQL Extension (mysql) mysql_get_client_info mysql_get_host_info mysql_get_proto_info phpversion 1.4.30. mysql_info Copyright 1997-2008 the PHP Documentation Group. • mysql_info Get information about the most recent query Description string mysql_info(resource link_identifier); Returns detailed information about the last query. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns information about the statement on success, or FALSE on failure. See the example below for which statements provide inform- ation, and what the returned value may look like. Statements that are not listed will return FALSE . Examples Example 1.37. Relevant MySQL Statements Statements that return string values. The numbers are only for illustrating purpose; their values will correspond to the query. INSERT INTO ... SELECT ... String format: Records: 23 Duplicates: 0 Warnings: 0 INSERT INTO ... VALUES (...),(...),(...)... String format: Records: 37 Duplicates: 0 Warnings: 0 LOAD DATA INFILE ... String format: Records: 42 Deleted: 0 Skipped: 0 Warnings: 0 ALTER TABLE String format: Records: 60 Duplicates: 0 Warnings: 0 UPDATE String format: Rows matched: 65 Changed: 65 Warnings: 0 Notes Note mysql_info returns a non- FALSE value for the INSERT ... VALUES statement only if multiple value lists are spe- cified in the statement. See Also 39
  • 44. MySQL Extension (mysql) mysql_affected_rows mysql_insert_id mysql_stat 1.4.31. mysql_insert_id Copyright 1997-2008 the PHP Documentation Group. • mysql_insert_id Get the ID generated in the last query Description int mysql_insert_id(resource link_identifier); Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established. Examples Example 1.38. mysql_insert_id example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('mydb'); mysql_query("INSERT INTO mytable (product) values ('kossu')"); printf("Last inserted record has id %dn", mysql_insert_id()); ?> Notes Caution mysql_insert_id will convert the return type of the native MySQL C API function mysql_insert_id() to a type of long (named int in PHP). If your AUTO_INCREMENT column has a column type of BIGINT (64 bits) the con- version may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation. Note 40
  • 45. MySQL Extension (mysql) Because mysql_insert_id acts on the last performed query, be sure to call mysql_insert_id immediately after the query that generates the value. Note The value of the MySQL SQL function LAST_INSERT_ID() always contains the most recently generated AUTO_INCREMENT value, and is not reset between queries. See Also mysql_query mysql_info 1.4.32. mysql_list_dbs Copyright 1997-2008 the PHP Documentation Group. • mysql_list_dbs List databases available on a MySQL server Description resource mysql_list_dbs(resource link_identifier); Returns a result pointer containing the databases available from the current mysql daemon. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values Returns a result pointer resource on success, or FALSE on failure. Use the mysql_tablename function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array. Examples Example 1.39. mysql_list_dbs example <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $db_list = mysql_list_dbs($link); while ($row = mysql_fetch_object($db_list)) { echo $row->Database . "n"; } ?> The above example will output something similar to: database1 database2 41
  • 46. MySQL Extension (mysql) database3 Notes Note For backward compatibility, the following deprecated alias may be used: mysql_listdbs See Also mysql_db_name mysql_select_db 1.4.33. mysql_list_fields Copyright 1997-2008 the PHP Documentation Group. • mysql_list_fields List MySQL table fields Description resource mysql_list_fields(string database_name, string table_name, resource link_identifier); Retrieves information about the given table name. This function is deprecated. It is preferable to use mysql_query to issue a SQL SHOW COLUMNS FROM table [LIKE 'name'] statement instead. Parameters database_name The name of the database that's being queried. table_name The name of the table that's being queried. link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect is assumed. If no such link is found, it will try to create one as if mysql_connect was called with no arguments. If no connection is found or established, an E_WARNING level error is generated. Return Values A result pointer resource on success, or FALSE on failure. The returned result can be used with mysql_field_flags, mysql_field_len, mysql_field_name and mysql_field_type. Examples Example 1.40. Alternate to deprecated mysql_list_fields <?php 42
  • 47. MySQL Extension (mysql) $result = mysql_query("SHOW COLUMNS FROM sometable"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { print_r($row); } } ?> The above example will output something similar to: Array ( [Field] => id [Type] => int(7) [Null] => [Key] => PRI [Default] => [Extra] => auto_increment ) Array ( [Field] => email [Type] => varchar(100) [Null] => [Key] => [Default] => [Extra] => ) Notes Note For backward compatibility, the following deprecated alias may be used: mysql_listfields See Also mysql_field_flags mysql_info 1.4.34. mysql_list_processes Copyright 1997-2008 the PHP Documentation Group. • mysql_list_processes List MySQL processes Description resource mysql_list_processes(resource link_identifier); Retrieves the current MySQL server threads. Parameters link_identifier The MySQL connection. If the link identifier is not specified, the last link opened by 43