mysql_result() function in PHP

What is mysql_result() function in PHP?
How does mysql_result() works?

Explanation

The mysql_result() function returns the value of a field in a recordset.
Syntax
mixed mysql_result ( resource result, int row [, mixed field])

Returns the field value on success, or FALSE on failure.
mysql_result() fetches a single field from a MySQL result set. The function accepts two or three arguments.
The first argument should be a mysql result handle returned by mysql_db_query() or mysql_query().
The second argument should be the result row number from which to fetch the field, specified as an offset. Row offsets start at 0 representing first row, 1 representing 2nd row and so on.
The optional third argument can contain a field offset or a field name. If the argument is not set, a field offset of 0 is assumed. Field offsets start at 0 representing the first column of result row, 1 representing the second column and so on.
Example

<?php
//Attempt to connect to the default database server
$conn = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die ("Could not connect");
//select database
$db = mysql_select_db('my_database',$conn);
//query to be executed
$sql = "SELECT * from emp_table";
//execute query
$result = mysql_query($sql,$conn);
// query result passed to mysql_result function to return the value of a field
echo mysql_result($result,2); //outputs third employee's name
mysql_close($conn);
?>

In the above code query result is passed to the mysql_query function with the offset value 2 inorder to retrieve the employees name of third record from the table.
you can iterate in a loop to find the employee name of all the resultant record by passing the field name instead of offset. Code is given below
Example

<?php
//Attempt to connect to the default database server
$conn = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die ("Could not connect");
//select database
$db = mysql_select_db('my_database',$conn);
//query to be executed
$sql = "SELECT * from emp_table";
//execute query
$result = mysql_query($sql,$conn);
//iterate in a loop to return employee name of all the records
for($i=0;$i < mysql_num_rows($result);++$i){
// query result passed to mysql_result function to return the value of a field
echo mysql_result($result,$i,name);
}
mysql_close($conn);
?>

See also: mysql_fetch_row() , mysql_fetch_array() , mysql_fetch_assoc() and mysql_fetch_object().

PHP Topics


Ask Questions

Ask Question