You are on page 1of 17

MySql Function

Connecting to the MySql Db Engine ( mysql_connect() ) Mysql_connect is used to establish a connection to the mysql Db engine running in memory on the local computer or on an entirely different computer. Syntex:mysql_connect(servername ,username ,password)

Parameters server is the MySQL server, which can be URLs, port numbers, and so on. The username and password argument are the MySQL username and password. The mysql_connect function returns a connection object if successful, FALSE otherwise. The value return by this function should be stored in a variable. $str=mysql_connect(localhost,$username,$password) Since the mysql Db engine can reside on a completely different computer , it is good programming practice to verify that MySQL Db Connection was established successfully. The connection usually fails due to one of the following reason: The server is unavailable or inaccessible due to network outage. The username and password combination passed to mysql_connect() is not accepted by the server. $str= @mysql_connect(localhost,$username,$password) If(!$str) { die(Database Connection failed); } The @ symbol in front of mysql_connect informs mysql_connect() that if the Db connection failed do nothing. Hence no system error will be displayed if the Db connection failed. Selecting the Database( mysql_select_db() ) After connecting to server we select the database using mysql_select_db() function. Syntax: mysql_select_db(database_name,link_identifier)

Parameter: The first parameter is the database name The second parameter is an optional parameter. It is a valid connection identifier that is retured by mysql_connect(). This parameter inform the php interpreter which database connection to use while selecting the database. When the second parameter omitted mysql_select_db() automatically uses the current active connection. <?php $username=root; $password=; $str= mysql_connect(localhost,$username,$password); if(!$str) { die(Database Connection failed); } $db=mysql_select_db(student,$str); if(!$db) {
Deependra Rastogi Page 1

MySql Function
die(Database Connection Failed); } ?> Executing Command (mysql_query()) To connect to a MySQL table for the purpose of the table data manipulation use the built in PHP function mysql_query(). mysql_query() accepts a variable which was previously loaded with the query string. Syntax: mysql_query(query,result_type)

Parameter:

query is the resource returned by the mysql_query function- thats the data table you have recovered from the database. result_type is the type of array that you want.

Example:<?php $username=root; $password=; $str= mysql_connect(localhost,$username,$password); if(!$str) { die(Database Connection failed); } mysql_select_db(student) or die(Database Connection Failed); echo The Mysql Database Connection Established; $query=Create table stud( Studid Integer(3), StudName Varchar2(20)); if(mysql_query($query)) { echo <br>Table Successfully Created; } else { echo <br>Error Creating table; } ?> mysql_query() provides a functional interface via which database table can be queried. It accepts a parameter which corresponds to an sql query. The useful thing about using this technique is that mysql_query() can be used to fire different query string against a table. Inserting data into table Data can be inserted into table using php program by using an appropriate INSERT statement. The INSERT INTO statement tells the PHP interpreter to append to table with value enclosed with its parenthesis. Example:<?php $username=root; $password=; $str= mysql_connect(localhost,$username,$password);
Deependra Rastogi Page 2

MySql Function
if(!$str) { die(Database Connection failed); } mysql_select_db(student) or die(Database Connection Failed); echo The Mysql Database Connection Established; $query=Insert into stud (Studid,StudName) values (101,Kamal); if(mysql_query($query)) { echo <br>Data Successfully Saved; } else { echo <br>Error Saving data; } mysql_close($str); ?> Displaying the Table data (mysql_fatch_array()) This function return a single associative array from a result set storing each entry in the record against a respective field name. Syntax: mysql_fatch_array(query,result_type)

Parameter: result is the resource returned by the mysql_query function- thats the data table youve recovered from the database. Result_type is the type of array that you want. This value is constant and can take the following values: MYSQL_ASSOC, MYSQL_NUM, and the default value of MYSQL_BOTH. Eaxample: <html> <body> <h1> Displaying Table Data with Mysql </h1> <?php $username=root; $password=; $str= mysql_connect(localhost,$username,$password); if(!$str) { die(Database Connection failed); } mysql_select_db(student) or die(Database Connection Failed); echo The Mysql Database Connection Established; $query=Select * from stud; $result = mysql_query($query) echo echo echo echo <table border=3>; <tr>; <th>Student Id</th><th>Student Name</th>; </tr>;

Deependra Rastogi

Page 3

MySql Function
while($row=mysql_fatch_array($result)) { echo <tr>; echo <td>,$row[StudId],</td><td>, $row[StudName],</td>; echo </tr>; } echo </table>; mysql_close($str); ?> </body> </html> mysql_num_rows() use to find the number of rows in a result set returned by a given query.it takes result set pointer as as argument: Syntax int mysql_num_rows(result set pointer)

This command is only valid for select statelment. To retrieve the number of rows affected by a INSERT, DELETE, UPDATE query use mysql_affected_rows(). Parameter: Result set pointer- The result come from call to mysql_query. Return value: The number of rows in a result set on success, or FALSE on failure. <html> <body> <h1> Displaying the number of row </h1> <?php $username=root; $password=; $str= mysql_connect(localhost,$username,$password); if(!$str) { die(Database Connection failed); } mysql_select_db(student) or die(Database Connection Failed); echo The Mysql Database Connection Established; $query=Select * from stud; $result = mysql_query($query); $num_row=mysql_num_rows($result); echo Number of rows:- .$num_row; mysql_close($str); ?> </body> </html> mysql_affected_rows() use instead of mysql_num_rows() to get the number of rows affected by INSERT, UPDATE, OR DELETE commands. It takes an optional link ID argument: Syntax:int mysql_affected_rows(resource link_identifier)

Parameter:
Deependra Rastogi Page 4

MySql Function
The Mysql connection, if the link identifier is not specified, the last link opened by mysql_connect() is assumed. Return the number of rows affected rows on success, and -1 if the last query failed.

Example <html> <body> <h1> Displaying the number of rows affected </h1> <?php $username=root; $password=; $str= mysql_connect(localhost,$username,$password); if(!$str) { die(Database Connection failed); } mysql_select_db(student) or die(Database Connection Failed); echo The Mysql Database Connection Established; $query=delete from stud where studid<10; $result = mysql_query($query); $num_row=mysql_affected_rows($result); echo Number of rows:- .$num_row; mysql_close($str); ?> </body> </html> mysql_fatch_row() use to retrieve the row of records returned from the server. It takes a result set pointer returned from a previous query, and returned an array corresponding to the fetched row. Syntax Parameter: The result_set that is being evaluated. This result come from a call to mysql_query() Returns an numerical array that corresponding to the fetched row or false if there are no more rows. mysql_fatch_row fatch 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. Example <html> <body> <h1> Displaying the row </h1> <?php $username=root; $password=;
Deependra Rastogi Page 5

array mysql_fatch_row(result_set)

MySql Function
$str= mysql_connect(localhost,$username,$password); if(!$str) { die(Database Connection failed); } mysql_select_db(student) or die(Database Connection Failed); echo The Mysql Database Connection Established; $query=select * from stud where studid=9; $result = mysql_query($query); $row=mysql_fatch_row($result); echo $row[0]; echo $row[1]; mysql_close($str); ?> </body> </html> mysql_fatch_object() This function returns a single object from a result set, storing each entry as a property of that object. The properties are named according to the field name. Syntax object mysql_fatch_object(result_set)

Parameter: The result_set that is being evaluated. This result comes from a call to mysql_query(). Return an object with properties that corresponds to the fetched row, or false if there are no more row. Example <html> <body> <h1> Displaying the row </h1> <?php $username=root; $password=; $str= mysql_connect(localhost,$username,$password); if(!$str) { die(Database Connection failed); } mysql_select_db(student) or die(Database Connection Failed); echo The Mysql Database Connection Established; $query=select * from stud; $result = mysql_query($query); While($row=mysql_fatch_object($result)) { echo $rowstudid; echo $rowstudName; } mysql_close($str); ?> </body>
Deependra Rastogi Page 6

MySql Function

mysql_list_dbs Description resource mysql_list_dbs ( [resource link_identifier]) mysql_list_dbs() will return a result pointer containing the databases available from the current mysql daemon. Use the mysql_tablename() function to traverse this result pointer, or any function for result tables. Example <?php $link = mysql_connect('localhost', 'root', ''); $db_list = mysql_list_dbs($link); while ($row mysql_fetch_object($db_list)) { echo $row->Database . "\n"; } ?> =

The above example would produce the following output: database 1 database 2 database 3 ...

mysql_field_name (PHP 3, PHP 4 ) mysql_field_name -- Get the name of the specified field in a result Description string mysql_field_name ( resource result, int field_index) mysql_field_name() returns the name of the specified field index. result must be a valid result identifier and field_index is the numerical offset of the field. Note: field_index starts at 0.
Deependra Rastogi Page 7

MySql Function
e.g. The index of the third field would actually be 2, the index of the fourth field would be 3 and so on. Example 1. mysql_field_name() example /* The users table consists of three fields: * user_id * username * password. */ <?php $link = mysql_connect('localhost', "root", "); mysql_select_db($dbname, $link) or die("Could not set $dbname"); $res = mysql_query("select * from users", $link); echo mysql_field_name($res, 0) . "\n"; echo mysql_field_name($res, 2); ?> The above example would produce the following output: user_id passwor d mysql_list_fields mysql_list_fields -- List MySQL result fields Description resource mysql_list_fields ( string database_name, string table_name [, resource link_identifier]) mysql_list_fields() retrieves information about the given tablename. Arguments are the database name and the table name Example <?php $link = mysql_connect('localhost', 'root', ''); $fields = mysql_list_fields("database1", "table1", $link); $columns = mysql_num_fields($fields); for ($i = 0; $i < $columns; $i++) { echo mysql_field_name($fields, $i) . "\n"; } The above example would produce the following output: field 1 field 2 field
Deependra Rastogi Page 8

MySql Function
3 ...

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. Parameter 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 MySQL Extension (mysql) 30 The name of the table on success. example <?php $str= mysql_connect(localhost,$username,$password); if(!$str) or die(Database Connection failed); mysql_select_db(student) or die(Database Connection Failed); $query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = country; $result = mysql_query($query); for ($i = 0; $i < mysql_num_fields($result); ++$i) { $table = mysql_field_table($result, $i); $field = mysql_field_name($result, $i); echo "$table: $field\n"; } ?>

mysql_field_type (PHP 3, PHP 4 ) 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 instead. The field type will be one of "int", "real", "string", "blob", and others as detailed in the MySQL documentation. Example 1. MySQL field types
Deependra Rastogi Page 9

MySql Function

<?php mysql_connect("localhost", "root", ""); 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); echo $type." ".$name." ".$len."."\n"; } mysql_free_result($result); mysql_close(); ?>

The above example would produce the following output: 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 string dl 128 string type 9 mysql_field_len Returns the length of the specified field Description int mysql_field_len(resource result,int field_offset); 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 mysql_connect("localhost", "root", ""); mysql_select_db("mysql"); $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) {
Deependra Rastogi Page 10

MySql Function
echo 'Could not run query: ' . mysql_error(); exit; } $length = mysql_field_len($result, 0); echo $length; ?> mysql_list_tables (PHP 3, PHP 4 ) mysql_list_tables -- List tables in a MySQL database Description resource mysql_list_tables ( string database [, resource link_identifier]) mysql_list_tables() takes a database name and returns a result pointer much like the mysql_query() function. You can use the mysql_tablename() function to extract the actual table names from the result pointer, or any other result table function such as mysql_fetch_assoc(). The database parameter is the name of the database to retrieve the list of tables from. Upon failure, mysql_list_tables() returns FALSE. For downward compatibility, the function alias named mysql_listtables() can be used. This is deprecated however and is not recommended. Example 1. mysql_list_tables Example <?php $dbname = 'mysql_dbname'; if (!mysql_connect(localhost', 'root', '')) { print 'Could not connect to mysql'; exit; } $result mysql_list_tables($dbname); =

if (!$result) { print "DB Error, could not list tables\n"; print 'MySQL Error: ' . mysql_error(); exit; } while ($row mysql_fetch_row($result)) { print "Table: $row[0]\n"; } mysql_free_result($result);
Deependra Rastogi Page 11

MySql Function
?> mysql_fetch_assoc (PHP 4 >= 4.0.3) mysql_fetch_assoc -- Fetch a result row as an associative array Description array mysql_fetch_assoc ( resource result) Returns an associative array that corresponds to the fetched row, or FALSE if there are no more rows. mysql_fetch_assoc() is equivalent to calling mysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array. This is the way mysql_fetch_array() originally worked. If you need the numeric indices as well as the associative, use mysql_fetch_array(). 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 example at the mysql_fetch_array() description about aliases. 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. Example 1. mysql_fetch_assoc() <?php mysql_connect("localhost", "root, ""); mysql_select_db("mydb"); $query = "select * from table"; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) { echo $row["user_id"]; echo $row["fullname"]; } mysql_free_result($result); ?> 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 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

Deependra Rastogi

Page 12

MySql Function
Return Values Returns TRUE on success or FALSE on failure. MySQL Extension (mysql) 32 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 <?php mysql_connect("localhost", "root", ""); mysql_select_db("mysql"); $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); mysql_free_result($result); echo $row['id']; echo $row['email']; ?> mysql_num_fields Get number of fields in result Description int mysql_num_fields(resource result); Retrieves the number of fields from a query. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. Return Values Returns the number of fields in the result set resource on success or FALSE on failure. example <?php mysql_connect("localhost", "root", ""); mysql_select_db("mysql"); $result = mysql_query("SELECT id,email FROM people WHERE id = '42'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } /* returns 2 because id,email === two fields */ echo mysql_num_fields($result); ?> mysql_error (PHP 3, PHP 4 ) mysql_error -- Returns the text of the error message from previous MySQL operation Description string mysql_error ( [resource link_identifier])
Deependra Rastogi Page 13

MySql Function
Returns the error text from the last MySQL function, or '' (the empty string) if no error occurred. 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. Example 1. mysql_error Example <?php mysql_connect("localhost", "root", ""); mysql_select_db("nonexistentdb"); echo mysql_errno() . ": " . mysql_error(). "\n"; mysql_select_db("kossu"); mysql_query("SELECT * FROM nonexistenttable"); echo mysql_errno() . ": " . mysql_error() . "\n"; ?> The above example would produce the following output: 1049: Unknown database 'nonexistentdb' 1146: Table 'kossu.nonexistenttable' doesn't exist mysql_close (PHP 3, PHP 4 ) mysql_close -- Close MySQL connection Description bool mysql_close ( [resource link_identifier]) Returns TRUE on success, FALSE on failure. mysql_close() closes the 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. Note: mysql_close() will not close persistent links created by mysql_pconnect(). Example 1. MySQL close example <?php $link = mysql_connect("localhost", "mysql_user", "mysql_password") or exit("Could not connect"); print ("Connected successfully"); mysql_close($link);
Deependra Rastogi Page 14

MySql Function
?> mysql_create_db (PHP 3, PHP 4 ) 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. Returns TRUE on success, FALSE on failure. Example 1. MySQL create database example <?php $link = mysql_pconnect("localhost", "mysql_user", "mysql_password") or exit("Could not connect"); if (mysql_create_db("my_db")) { print ("Database created successfully\n"); } else { printf ("Error creating database: %s\n", mysql_error ()); } ?> For downwards compatibility mysql_createdb() can also be used. This is deprecated, however. Note: The function mysql_create_db() is deprecated. It is preferable to use mysql_query() to issue a SQL CREATE DATABASE Statement instead. mysql_db_name (PHP 3>= 3.0.6, PHP 4 ) mysql_db_name -- Get result data Description string mysql_db_name ( resource result, int row [, mixed field]) mysql_db_name() takes as its first parameter the result pointer from a call to mysql_list_dbs(). The row parameter is an index into the result set. If an error occurs, FALSE is returned. Use mysql_errno() and mysql_error() to determine the nature of the error. Example 1. mysql_db_name() example <?php error_reporting(E_ALL); mysql_connect('dbhost', 'username',
Deependra Rastogi Page 15

MySql Function
'password'); $db_list = mysql_list_dbs(); $i = 0; $cnt = mysql_num_rows($db_list); while ($i < $cnt) { echo mysql_db_name($db_list, $i) . "\n"; $i++; } ?> mysql_result Get result data Description string mysql_result(resource result, int row, mixed field= =0); Retrieves the contents of one cell from a MySQL result set. When working on large result sets, you should consider using one of the functions that fetch an entire row (specified below). As these functions return the contents of multiple cells in one function call, they're MUCH quicker than mysql_result. Also, note that specifying a numeric offset for the field argument is much quicker than specifying a fieldname or tablename.fieldname argument. Parameters result The result resource that is being evaluated. This result comes from a call to mysql_query. row The row number from the result that's being retrieved. Row numbers start at 0. field The name or offset of the field being retrieved. It can be the field's offset, the field's name, or the field's table dot field name (tablename.fieldname). If the column name has been aliased ('select foo as bar from...'), use the alias instead of the column name. If undefined, the first field is retrieved. Return Values The contents of one cell from a MySQL result set on success, or FALSE on failure. Examples example <?php $link = mysql_connect('localhost', 'root', ); if (!$link) { die('Could not connect: ' . mysql_error()); } if (!mysql_select_db('database_name')) { die('Could not select database: ' . mysql_error()); } $result = mysql_query('SELECT name FROM work.employee'); if (!$result) { die('Could not query:' . mysql_error()); } echo mysql_result($result, 2); // outputs third employee's name mysql_close($link); ?>

Deependra Rastogi

Page 16

MySql Function
mysql_tablename (PHP 3, PHP 4 ) mysql_tablename -- Get table name of field Description string mysql_tablename ( resource result, int i) mysql_tablename() takes a result pointer returned by the mysql_list_tables() function as well as an integer index and returns the name of a table. The mysql_num_rows() function may be used to determine the number of tables in the result pointer. Example 1. mysql_tablename() Example <?php mysql_connect("localhost", "mysql_user", "mysql_password"); $result = mysql_list_tables("mydb"); for ($i = 0; $i < mysql_num_rows($result); $i++) printf ("Table: %s\n", mysql_tablename($result, $i)); mysql_free_result($result); ?>

Deependra Rastogi

Page 17

You might also like